diff --git a/LeanPool/KLRandomness.lean b/LeanPool/KLRandomness.lean new file mode 100644 index 0000000000..f7f967337b --- /dev/null +++ b/LeanPool/KLRandomness.lean @@ -0,0 +1,25 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.BaseInvariance +public import LeanPool.KLRandomness.Separation + +/-! +# Kolmogorov–Loveland and Martin–Löf randomness + +Source: arxiv:2611.31004v1, url:https://github.com/bjoernkjoshanssen/klr/tree/81f5fef2de3142aad714624033a5aa4f12031a6b +Authors: Bjørn Kjos-Hanssen +Status: verified +Main declarations: `Klr.martinLofRandom_ssubset_kolmogorovLovelandRandom`, + `Klr.exists_not_martinLofRandom_no_partial_rational_success`, + `Klr.binary_random_ssubset_baseFour_random` +Tags: algorithmic randomness, computability, martingales, effective measure theory +MSC: 03D32, 03B35 +-/ diff --git a/LeanPool/KLRandomness/Affine.lean b/LeanPool/KLRandomness/Affine.lean new file mode 100644 index 0000000000..b525938b97 --- /dev/null +++ b/LeanPool/KLRandomness/Affine.lean @@ -0,0 +1,189 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import Mathlib.Algebra.Field.ZMod +public import Mathlib.LinearAlgebra.FiniteDimensional.Lemmas +public import Mathlib.Data.ZMod.Basic +public import Mathlib.SetTheory.Cardinal.Finite +public import Mathlib.FieldTheory.Finiteness +import Mathlib.Tactic.Abel +import Mathlib.Tactic.Positivity + +/-! +# The algebra behind fair and forced answers + +Section 3 of Liu and Meng, arXiv:2611.31004v1, removes the queried column `c` +from the unread matrix. Let `D` be the linear map given by the other unread +columns, and `z` the remaining syndrome. The two possible answers have +completion fibers `D x = z` and `D x = z - c`. + +If `c` is in the range of `D`, translation gives a bijection between the +fibers. If `c` is outside the range, the two fibers cannot both be nonempty. +The dimension of the span drops by exactly one in the latter case. + +These algebraic statements are proved over any field. They apply in +particular to binary parity equations over `ZMod 2`. The measure-theoretic +statement about conditioning an adaptive transcript is a subsequent task. +-/ + +@[expose] public section + +namespace Klr.Affine + +variable {K V W : Type*} [Field K] [AddCommGroup V] [AddCommGroup W] + [Module K V] [Module K W] + +/-- All completions realizing a given residual syndrome. -/ +def Fiber (D : V →ₗ[K] W) (z : W) := {x : V // D x = z} + +/-- Adding back the queried column to the span of the other columns. -/ +def withColumn (D : V →ₗ[K] W) (c : W) : Submodule K W := + LinearMap.range D ⊔ Submodule.span K {c} + +/-- Every nonempty affine fiber is a translate of the kernel. -/ +def fiberEquivKer (D : V →ₗ[K] W) {z : W} (u : V) (hu : D u = z) : + Fiber D z ≃ LinearMap.ker D where + toFun x := ⟨x.val - u, by + change D (x.val - u) = 0 + rw [map_sub, x.property, hu, sub_self]⟩ + invFun x := ⟨x.val + u, by + have hx : D x.val = 0 := x.property + rw [map_add, hx, hu, zero_add]⟩ + left_inv x := by apply Subtype.ext; simp + right_inv x := by apply Subtype.ext; simp + +/-- Counting solutions of a full-row-rank finite-dimensional affine system. -/ +theorem card_fiber_of_surjective [Module.Finite K V] + (D : V →ₗ[K] W) (hD : Function.Surjective D) (z : W) : + Nat.card (Fiber D z) = Nat.card K ^ (Module.finrank K V - Module.finrank K W) := by + obtain ⟨u, hu⟩ := hD z + rw [Nat.card_congr (fiberEquivKer D u hu), Module.natCard_eq_pow_finrank (K := K)] + have hd := D.finrank_range_add_finrank_ker + rw [LinearMap.range_eq_top.mpr hD, finrank_top] at hd + congr 1 + omega + +/-- A rank-`r` system of parity equations on `m` bits has `2^(m-r)` solutions. -/ +theorem card_binary_fiber {m r : ℕ} + (D : (Fin m → ZMod 2) →ₗ[ZMod 2] (Fin r → ZMod 2)) + (hD : Function.Surjective D) (z : Fin r → ZMod 2) : + Nat.card (Fiber D z) = 2 ^ (m - r) := by + simpa using card_fiber_of_surjective D hD z + +/-- The fraction of assignments satisfying `r` independent parity equations +is exactly `2⁻ʳ`. This is the finite counting form of the fair-coin measure +calculation used to build the Martin-Löf test. -/ +theorem binary_fiber_fraction {m r : ℕ} + (D : (Fin m → ZMod 2) →ₗ[ZMod 2] (Fin r → ZMod 2)) + (hD : Function.Surjective D) (z : Fin r → ZMod 2) : + (Nat.card (Fiber D z) : ℚ) / Nat.card (Fin m → ZMod 2) = (1 / 2 : ℚ) ^ r := by + have hd := D.finrank_range_add_finrank_ker + rw [LinearMap.range_eq_top.mpr hD, finrank_top] at hd + simp only [Module.finrank_pi, Fintype.card_fin] at hd + have hr : r ≤ m := by omega + rw [card_binary_fiber D hD z, Nat.card_fun, Nat.card_zmod, Nat.card_fin] + push_cast + have hp : (2 : ℚ) ^ m = 2 ^ (m - r) * 2 ^ r := by + rw [← pow_add, Nat.sub_add_cancel hr] + rw [hp, div_mul_eq_div_div, div_self (by positivity : (2 : ℚ) ^ (m - r) ≠ 0)] + simp + +/-- Subtracting a preimage of the queried column switches the possible +answer while preserving the residual affine equations. -/ +def fiberEquiv (D : V →ₗ[K] W) (z : W) {c : W} (u : V) (hu : D u = c) : + Fiber D z ≃ Fiber D (z - c) where + toFun x := ⟨x.val - u, by simp [map_sub, x.property, hu]⟩ + invFun x := ⟨x.val + u, by simp [map_add, x.property, hu]⟩ + left_inv x := by apply Subtype.ext; simp + right_inv x := by apply Subtype.ext; simp + +/-- When deleting a column preserves the span, both bit values have equally +many completions. For a finite uniform solution space this is the counting +identity behind a fair conditional answer. -/ +theorem card_fiber_eq_of_mem_range (D : V →ₗ[K] W) (z : W) {c : W} + (hc : c ∈ LinearMap.range D) : + Nat.card (Fiber D z) = Nat.card (Fiber D (z - c)) := by + obtain ⟨u, hu⟩ := hc + exact Nat.card_congr (fiberEquiv D z u hu) + +theorem nonempty_fiber_iff_of_mem_range (D : V →ₗ[K] W) (z : W) {c : W} + (hc : c ∈ LinearMap.range D) : + Nonempty (Fiber D z) ↔ Nonempty (Fiber D (z - c)) := by + obtain ⟨u, hu⟩ := hc + exact (fiberEquiv D z u hu).nonempty_congr + +/-- Two feasible answers would express the queried column as a difference +of images of the remaining columns. -/ +theorem mem_range_of_both_fibers (D : V →ₗ[K] W) (z c : W) + (h₀ : Nonempty (Fiber D z)) (h₁ : Nonempty (Fiber D (z - c))) : + c ∈ LinearMap.range D := by + obtain ⟨x₀⟩ := h₀ + obtain ⟨x₁⟩ := h₁ + refine ⟨x₀.val - x₁.val, ?_⟩ + rw [map_sub, x₀.property, x₁.property] + abel + +/-- If deleting the queried column loses span, at most one answer is +compatible. Compatibility of the observed history supplies existence. -/ +theorem not_both_fibers_of_not_mem_range (D : V →ₗ[K] W) (z : W) {c : W} + (hc : c ∉ LinearMap.range D) : + ¬ (Nonempty (Fiber D z) ∧ Nonempty (Fiber D (z - c))) := by + rintro ⟨h₀, h₁⟩ + exact hc (mem_range_of_both_fibers D z c h₀ h₁) + +/-- For a compatible history, an answer is forced exactly when the queried +column is outside the span of the other unread columns. -/ +theorem forced_iff_not_mem_range (D : V →ₗ[K] W) (z c : W) + (compatible : Nonempty (Fiber D z) ∨ Nonempty (Fiber D (z - c))) : + (¬ (Nonempty (Fiber D z) ∧ Nonempty (Fiber D (z - c)))) ↔ + c ∉ LinearMap.range D := by + constructor + · intro h hc + have he := nonempty_fiber_iff_of_mem_range D z hc + rcases compatible with h₀ | h₁ + · exact h ⟨h₀, he.mp h₀⟩ + · exact h ⟨he.mpr h₁, h₁⟩ + · exact not_both_fibers_of_not_mem_range D z + +theorem withColumn_eq_of_mem_range (D : V →ₗ[K] W) {c : W} + (hc : c ∈ LinearMap.range D) : withColumn D c = LinearMap.range D := by + apply sup_eq_left.mpr + apply Submodule.span_le.mpr + intro x hx + rcases Set.mem_singleton_iff.mp hx with rfl + exact hc + +/-- A column outside the remaining span raises the rank by exactly one. -/ +theorem finrank_withColumn_of_not_mem_range [Module.Finite K W] + (D : V →ₗ[K] W) {c : W} (hc : c ∉ LinearMap.range D) : + Module.finrank K (withColumn D c) = Module.finrank K (LinearMap.range D) + 1 := by + exact Submodule.finrank_sup_span_singleton hc + +/-- The rank-drop criterion in Section 3, expressed without choosing bases. -/ +theorem rank_drop_iff_not_mem_range [Module.Finite K W] + (D : V →ₗ[K] W) (c : W) : + Module.finrank K (LinearMap.range D) < Module.finrank K (withColumn D c) ↔ + c ∉ LinearMap.range D := by + by_cases hc : c ∈ LinearMap.range D + · rw [withColumn_eq_of_mem_range D hc] + simp [hc] + · rw [finrank_withColumn_of_not_mem_range D hc] + simp [hc] + +/-- A compatible query is forced exactly when deleting its column lowers +the rank. This is the algebraic part of the paper's adaptive-query lemma. -/ +theorem forced_iff_rank_drop [Module.Finite K W] + (D : V →ₗ[K] W) (z c : W) + (compatible : Nonempty (Fiber D z) ∨ Nonempty (Fiber D (z - c))) : + (¬ (Nonempty (Fiber D z) ∧ Nonempty (Fiber D (z - c)))) ↔ + Module.finrank K (LinearMap.range D) < Module.finrank K (withColumn D c) := by + rw [forced_iff_not_mem_range D z c compatible, rank_drop_iff_not_mem_range] + +end Klr.Affine diff --git a/LeanPool/KLRandomness/AffineAnswer.lean b/LeanPool/KLRandomness/AffineAnswer.lean new file mode 100644 index 0000000000..37e413466b --- /dev/null +++ b/LeanPool/KLRandomness/AffineAnswer.lean @@ -0,0 +1,313 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.AffineAnswerAlgebra +public import LeanPool.KLRandomness.AffineAnswerMeasure +import Mathlib.Tactic.NormNum + +/-! +# Conditional fair and forced answers after arbitrary rank loss + +The conditioning event contains a finite family of old block equations, one +disjoint block, and an actual adaptive transcript. No full-unread-rank +assumption is made. A kernel translation proves fairness when the queried +column is redundant; otherwise all compatible inputs agree on the answer. +The nonnull-history hypothesis is explicit in every conditional probability. +-/ + +@[expose] public section + +namespace Klr + +open MeasureTheory ProbabilityTheory AffineObservation FiniteMeasure StoppingTranscript +open scoped ENNReal + +namespace ScanRule + +/-- The next query has not already appeared in the prescribed transcript. -/ +theorem query_not_mem_queriedPositions (π : ScanRule) (v : List Bool) : + π.query v ∉ π.queriedPositions v := by + intro h + obtain ⟨i, _, hi⟩ := Finset.mem_image.mp h + exact π.fresh v i.val i.isLt hi + +/-- The query chosen from `v` is the only position added by its next answer. -/ +theorem queriedPositions_snoc (π : ScanRule) (v : List Bool) (b : Bool) : + π.queriedPositions (v ++ [b]) = insert (π.query v) (π.queriedPositions v) := by + apply Finset.Subset.antisymm + · intro q hq + obtain ⟨i, _, hi⟩ := Finset.mem_image.mp hq + have hlen : i.val ≤ v.length := by simpa using i.isLt + rcases lt_or_eq_of_le hlen with hlt | heq + · apply Finset.mem_insert_of_mem + refine Finset.mem_image.mpr ⟨⟨i.val, hlt⟩, Finset.mem_univ _, ?_⟩ + simpa only [List.take_append_of_le_length hlt.le] using hi + · apply Finset.mem_insert.mpr + left + simpa [heq] using hi.symm + · intro q hq + rcases Finset.mem_insert.mp hq with rfl | hq + · refine Finset.mem_image.mpr ⟨⟨v.length, by simp⟩, Finset.mem_univ _, ?_⟩ + simp + · exact π.queriedPositions_mono (List.prefix_append v [b]) hq + +/-- A prescribed transcript depends exactly on its finitely many queried coordinates. -/ +theorem dependsOn_inputEvent (π : ScanRule) (v : List Bool) : + DependsOn (fun X : Cantor => X ∈ inputEvent π v) (π.queriedPositions v : Set ℕ) := by + intro X Y hxy + apply propext + change π.transcript X v.length = v ↔ π.transcript Y v.length = v + rw [π.transcript_eq_iff, π.transcript_eq_iff] + constructor <;> intro h i hi + · rw [← hxy _ (π.query_mem_queriedPositions v ⟨i, hi⟩)] + exact h i hi + · rw [hxy _ (π.query_mem_queriedPositions v ⟨i, hi⟩)] + exact h i hi + +/-- Inputs realizing the same transcript agree at every position it queried. -/ +theorem inputEvent_agree (π : ScanRule) (v : List Bool) {X Y : Cantor} + (hX : X ∈ inputEvent π v) (hY : Y ∈ inputEvent π v) + {q : ℕ} (hq : q ∈ π.queriedPositions v) : X q = Y q := by + obtain ⟨i, _, rfl⟩ := Finset.mem_image.mp hq + exact ((π.transcript_eq_iff X v).mp hX i.val i.isLt).trans + ((π.transcript_eq_iff Y v).mp hY i.val i.isLt).symm + +end ScanRule + +namespace AffineBlock + +/-- Within this block, the next query adds its column to the observed set. -/ +theorem observed_snoc (B : AffineBlock) (π : ScanRule) (v : List Bool) + (hq : π.query v ∈ B.support) (b : Bool) : + B.observed π (v ++ [b]) = insert ⟨π.query v, hq⟩ (B.observed π v) := by + ext i + simp [observed, π.queriedPositions_snoc, Subtype.ext_iff] + +/-- The numerical rank after the next query is chosen before its answer is known. -/ +theorem remainingRank_snoc_answer_independent (B : AffineBlock) (π : ScanRule) + (v : List Bool) (b c : Bool) : + B.remainingRank π (v ++ [b]) = B.remainingRank π (v ++ [c]) := by + apply congrArg (fun S : Submodule (ZMod 2) (Fin B.rank → ZMod 2) => + Module.finrank (ZMod 2) S) + apply AffineAnswer.unreadMap_range_congr + simp only [observed, queriedPositions_append_singleton_eq π v b c] + +/-- Numerical remaining rank after the next query, expressed by deleting its column. -/ +theorem remainingRank_snoc_eq (B : AffineBlock) (π : ScanRule) (v : List Bool) + (hq : π.query v ∈ B.support) (b : Bool) : + B.remainingRank π (v ++ [b]) = Module.finrank (ZMod 2) + (LinearMap.range (unreadMap B.matrix (insert ⟨π.query v, hq⟩ (B.observed π v)))) := by + exact congrArg (fun S : Submodule (ZMod 2) (Fin B.rank → ZMod 2) => + Module.finrank (ZMod 2) S) + (AffineAnswer.unreadMap_range_congr B.matrix (B.observed_snoc π v hq b)) + +/-- The adaptive numerical rank-drop criterion, at any current remaining rank. -/ +theorem rank_drop_iff_nextColumn_not_mem (B : AffineBlock) (π : ScanRule) (v : List Bool) + (hq : π.query v ∈ B.support) : + B.remainingRank π (v ++ [false]) < B.remainingRank π v ↔ + AffineAnswer.column B.matrix ⟨π.query v, hq⟩ ∉ + LinearMap.range (unreadMap B.matrix (insert ⟨π.query v, hq⟩ (B.observed π v))) := by + rw [B.remainingRank_snoc_eq π v hq false] + exact AffineAnswer.rank_drop_iff_column_not_mem B.matrix (B.observed π v) + ⟨π.query v, hq⟩ (π.query_not_mem_queriedPositions v) + +end AffineBlock + +namespace AffineAnswer + +/-- Earlier equations, the current block equations, and the observed adaptive transcript. -/ +def history {κ : Type*} (old : κ → AffineBlock) (B : AffineBlock) + (π : ScanRule) (v : List Bool) : Set Cantor := + (AffineBlock.familyEvent old ∩ B.event) ∩ inputEvent π v + +theorem measurableSet_history {κ : Type*} [Finite κ] (old : κ → AffineBlock) + (B : AffineBlock) (π : ScanRule) (v : List Bool) : + MeasurableSet (history old B π v) := + ((AffineBlock.measurableSet_familyEvent old).inter B.measurableSet_event).inter + (measurableSet_inputEvent π v) + +/-- Conditioning the actual current stage law on the transcript is exactly conditioning +fair coin on all the corresponding equations and observations together. -/ +theorem cond_stage_transcript {κ : Type*} [Finite κ] (old : κ → AffineBlock) + (B : AffineBlock) (π : ScanRule) (v : List Bool) : + cond (cond fairCoin (AffineBlock.familyEvent old ∩ B.event)) (inputEvent π v) = + cond fairCoin (history old B π v) := + cond_cond_eq_cond_inter + ((AffineBlock.measurableSet_familyEvent old).inter B.measurableSet_event) + (measurableSet_inputEvent π v) fairCoin + +/-- Extend a vector on the block by zero on all other input positions. -/ +def blockVector (B : AffineBlock) (k : B.support → ZMod 2) (n : ℕ) : ZMod 2 := + if h : n ∈ B.support then k ⟨n, h⟩ else 0 + +@[simp] theorem blockVector_apply (B : AffineBlock) (k : B.support → ZMod 2) + (i : B.support) : blockVector B k i.val = k i := by + simp [blockVector, i.property] + +theorem coordinateValues_translate_blockVector (B : AffineBlock) + (k : B.support → ZMod 2) (X : Cantor) : + coordinateValues (fun i : B.support => i.val) (translate (blockVector B k) X) = + coordinateValues (fun i : B.support => i.val) X + k := by + funext i + simp [translate] + +theorem blockVector_eq_zero_on_queries (B : AffineBlock) (π : ScanRule) (v : List Bool) + (k : B.support → ZMod 2) (hk : observedPart (B.observed π v) k = 0) : + ∀ n ∈ π.queriedPositions v, blockVector B k n = 0 := by + intro n hn + by_cases hs : n ∈ B.support + · have hki : k ⟨n, hs⟩ = 0 := congrFun hk ⟨⟨n, hs⟩, hn⟩ + simpa [blockVector, hs] using hki + · simp [blockVector, hs] + +/-- An unread kernel vector preserves the entire compatible-history event. -/ +theorem translate_mem_history {κ : Type*} (old : κ → AffineBlock) (B : AffineBlock) + (hdis : ∀ j, Disjoint (old j).support B.support) (π : ScanRule) (v : List Bool) + (k : B.support → ZMod 2) (hkO : observedPart (B.observed π v) k = 0) + (hkD : B.matrix k = 0) (X : Cantor) : + translate (blockVector B k) X ∈ history old B π v ↔ X ∈ history old B π v := by + have hold : translate (blockVector B k) X ∈ AffineBlock.familyEvent old ↔ + X ∈ AffineBlock.familyEvent old := by + apply forall_congr' + intro j + apply translate_mem_of_dependsOn (old j).event (old j).support + (old j).dependsOn_event + intro n hn + simp [blockVector, Finset.disjoint_left.mp (hdis j) hn] + have hblock : translate (blockVector B k) X ∈ B.event ↔ X ∈ B.event := by + change B.matrix (coordinateValues _ (translate (blockVector B k) X)) = B.syndrome ↔ _ + rw [coordinateValues_translate_blockVector, map_add, hkD, add_zero] + rfl + have htrans := translate_mem_of_dependsOn (inputEvent π v) (π.queriedPositions v) + (π.dependsOn_inputEvent v) (blockVector B k) (blockVector_eq_zero_on_queries B π v k hkO) X + exact and_congr (and_congr hold hblock) htrans + +/-- A redundant queried column gives a fair conditional answer, regardless of how +much row rank has already been lost. Only compatibility of the history is required. -/ +theorem cond_next_bit_eq_half_of_column_mem {κ : Type*} [Finite κ] + (old : κ → AffineBlock) (B : AffineBlock) + (hdis : ∀ j, Disjoint (old j).support B.support) (π : ScanRule) (v : List Bool) + (hq : π.query v ∈ B.support) (hpos : fairCoin (history old B π v) ≠ 0) + (hc : column B.matrix ⟨π.query v, hq⟩ ∈ + LinearMap.range (unreadMap B.matrix (insert ⟨π.query v, hq⟩ (B.observed π v)))) + (b : Bool) : + (cond fairCoin (history old B π v)) (bitEvent (π.query v) b) = (1 / 2 : ℝ≥0∞) := by + obtain ⟨k, hkO, hkD, hkq⟩ := (column_mem_iff_kernel_vector B.matrix (B.observed π v) + ⟨π.query v, hq⟩ (π.query_not_mem_queriedPositions v)).mp hc + apply cond_bit_eq_half_of_translation (history old B π v) + (measurableSet_history old B π v) hpos (blockVector B k) + (translate_mem_history old B hdis π v k hkO hkD) (π.query v) _ b + simpa [blockVector, hq] using hkq + +/-- The next answer is fair whenever this query does not strictly decrease the +block's current numerical remaining rank. -/ +theorem cond_next_bit_eq_half_of_no_rank_drop {κ : Type*} [Finite κ] + (old : κ → AffineBlock) (B : AffineBlock) + (hdis : ∀ j, Disjoint (old j).support B.support) (π : ScanRule) (v : List Bool) + (hq : π.query v ∈ B.support) (hpos : fairCoin (history old B π v) ≠ 0) + (hnodrop : ¬B.remainingRank π (v ++ [false]) < B.remainingRank π v) (b : Bool) : + (cond fairCoin (history old B π v)) (bitEvent (π.query v) b) = (1 / 2 : ℝ≥0∞) := by + apply cond_next_bit_eq_half_of_column_mem old B hdis π v hq hpos _ b + by_contra hc + exact hnodrop ((B.rank_drop_iff_nextColumn_not_mem π v hq).mpr hc) + +/-- At a rank drop, every two inputs satisfying the equations and the fixed transcript +give the same answer. This is a pointwise conclusion, stronger than almost sure forcing. -/ +theorem next_bits_eq_of_rank_drop {κ : Type*} (old : κ → AffineBlock) (B : AffineBlock) + (π : ScanRule) (v : List Bool) (hq : π.query v ∈ B.support) + (hdrop : B.remainingRank π (v ++ [false]) < B.remainingRank π v) + {X Y : Cantor} (hX : X ∈ history old B π v) (hY : Y ∈ history old B π v) : + X (π.query v) = Y (π.query v) := by + apply boolEquivF2.injective + apply answer_eq_of_column_not_mem B.matrix (B.observed π v) ⟨π.query v, hq⟩ + (π.query_not_mem_queriedPositions v) + ((B.rank_drop_iff_nextColumn_not_mem π v hq).mp hdrop) + (x := coordinateValues (fun i : B.support => i.val) X) + (y := coordinateValues (fun i : B.support => i.val) Y) + · funext i + change boolEquivF2 (X i.val.val) = boolEquivF2 (Y i.val.val) + rw [π.inputEvent_agree v hX.2 hY.2 i.property] + · exact hX.1.2.trans hY.1.2.symm + +/-- At a rank drop in a compatible history, exactly one bit is possible; it has +conditional probability one and its opposite has conditional probability zero. -/ +theorem cond_next_bit_forced_of_rank_drop {κ : Type*} [Finite κ] + (old : κ → AffineBlock) (B : AffineBlock) (π : ScanRule) (v : List Bool) + (hq : π.query v ∈ B.support) (hpos : fairCoin (history old B π v) ≠ 0) + (hdrop : B.remainingRank π (v ++ [false]) < B.remainingRank π v) : + ∃ b : Bool, history old B π v ⊆ bitEvent (π.query v) b ∧ + (cond fairCoin (history old B π v)) (bitEvent (π.query v) b) = 1 ∧ + (cond fairCoin (history old B π v)) (bitEvent (π.query v) (!b)) = 0 := by + obtain ⟨X, hX⟩ := nonempty_of_measure_ne_zero hpos + have hsub : history old B π v ⊆ bitEvent (π.query v) (X (π.query v)) := by + intro Y hY + exact next_bits_eq_of_rank_drop old B π v hq hdrop hY hX + exact ⟨X (π.query v), hsub, cond_bit_eq_one_zero_of_subset (history old B π v) + (measurableSet_history old B π v) hpos (π.query v) (X (π.query v)) hsub⟩ + +/-- Fairness of the next answer is equivalent to absence of a strict rank decrease, +under the actual finite equations-and-transcript conditional law. -/ +theorem cond_next_answer_fair_iff_no_rank_drop {κ : Type*} [Finite κ] + (old : κ → AffineBlock) (B : AffineBlock) + (hdis : ∀ j, Disjoint (old j).support B.support) (π : ScanRule) (v : List Bool) + (hq : π.query v ∈ B.support) (hpos : fairCoin (history old B π v) ≠ 0) : + (∀ b : Bool, (cond fairCoin (history old B π v)) (bitEvent (π.query v) b) = + (1 / 2 : ℝ≥0∞)) ↔ ¬B.remainingRank π (v ++ [false]) < B.remainingRank π v := by + constructor + · intro hfair hdrop + obtain ⟨b, _, hb, _⟩ := cond_next_bit_forced_of_rank_drop old B π v hq hpos hdrop + have h := hfair b + rw [hb] at h + have hm := congrArg (fun a : ℝ≥0∞ => a * 2) h + rw [one_mul, one_div, ENNReal.inv_mul_cancel (by norm_num) (by norm_num)] at hm + norm_num at hm + · intro hnodrop b + exact cond_next_bit_eq_half_of_no_rank_drop old B hdis π v hq hpos hnodrop b + +/-- The same fair-or-rank-drop equivalence stated by first conditioning on all block +equations, then conditioning that genuine stage law on the observed transcript. -/ +theorem stage_next_answer_fair_iff_no_rank_drop {κ : Type*} [Finite κ] + (old : κ → AffineBlock) (B : AffineBlock) + (hdis : ∀ j, Disjoint (old j).support B.support) (π : ScanRule) (v : List Bool) + (hq : π.query v ∈ B.support) (hpos : fairCoin (history old B π v) ≠ 0) : + (∀ b : Bool, + (cond (cond fairCoin (AffineBlock.familyEvent old ∩ B.event)) (inputEvent π v)) + (bitEvent (π.query v) b) = (1 / 2 : ℝ≥0∞)) ↔ + ¬B.remainingRank π (v ++ [false]) < B.remainingRank π v := by + rw [cond_stage_transcript] + exact cond_next_answer_fair_iff_no_rank_drop old B hdis π v hq hpos + +/-- A fresh query outside every conditioned block is fair, independently of all +remaining block ranks. -/ +theorem cond_next_bit_eq_half_of_free {κ : Type*} [Finite κ] + (old : κ → AffineBlock) (B : AffineBlock) (π : ScanRule) (v : List Bool) + (hqB : π.query v ∉ B.support) (hqold : ∀ j, π.query v ∉ (old j).support) + (hpos : fairCoin (history old B π v) ≠ 0) (b : Bool) : + (cond fairCoin (history old B π v)) (bitEvent (π.query v) b) = (1 / 2 : ℝ≥0∞) := by + let z : ℕ → ZMod 2 := Pi.single (π.query v) 1 + have hz (S : Finset ℕ) (hq : π.query v ∉ S) : ∀ n ∈ S, z n = 0 := by + intro n hn + have hne : n ≠ π.query v := by intro h; exact hq (h ▸ hn) + simp [z, hne] + have hinv (X : Cantor) : translate z X ∈ history old B π v ↔ X ∈ history old B π v := by + have hold : translate z X ∈ AffineBlock.familyEvent old ↔ X ∈ AffineBlock.familyEvent old := by + apply forall_congr' + intro j + exact translate_mem_of_dependsOn (old j).event (old j).support + (old j).dependsOn_event z (hz _ (hqold j)) X + exact and_congr (and_congr hold + (translate_mem_of_dependsOn B.event B.support B.dependsOn_event z (hz _ hqB) X)) + (translate_mem_of_dependsOn (inputEvent π v) (π.queriedPositions v) + (π.dependsOn_inputEvent v) z (hz _ (π.query_not_mem_queriedPositions v)) X) + exact cond_bit_eq_half_of_translation (history old B π v) + (measurableSet_history old B π v) hpos z hinv (π.query v) (by simp [z]) b + +end AffineAnswer +end Klr diff --git a/LeanPool/KLRandomness/AffineAnswerAlgebra.lean b/LeanPool/KLRandomness/AffineAnswerAlgebra.lean new file mode 100644 index 0000000000..e2273a26cc --- /dev/null +++ b/LeanPool/KLRandomness/AffineAnswerAlgebra.lean @@ -0,0 +1,153 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.RemainingRank + +/-! +# The kernel criterion for a fair unread answer + +A query at an unread coordinate can be flipped while preserving all observed +values and equations exactly when its column is in the span of the other +unread columns. This does not require the remaining matrix to have full row +rank. Otherwise every two compatible assignments agree at the query. +-/ + +@[expose] public section + +namespace Klr.AffineAnswer + +open AffineObservation + +variable {ι : Type*} [DecidableEq ι] {r : ℕ} + +/-- The column of a linear system indexed by one coordinate. -/ +def column (D : (ι → ZMod 2) →ₗ[ZMod 2] (Fin r → ZMod 2)) (q : ι) : Fin r → ZMod 2 := + D (Pi.single q 1) + +omit [DecidableEq ι] in +/-- The unread image depends on the observed set, not its decision procedure. -/ +theorem unreadMap_range_congr + (D : (ι → ZMod 2) →ₗ[ZMod 2] (Fin r → ZMod 2)) + {O P : Set ι} [dO : DecidablePred (· ∈ O)] [dP : DecidablePred (· ∈ P)] + (h : O = P) : LinearMap.range (unreadMap D O) = LinearMap.range (unreadMap D P) := by + subst P + cases Subsingleton.elim dO dP + rfl + +/-- A vector vanishing on the observed coordinates splits into its next coordinate +and its remaining unread part. -/ +theorem unread_insert_decomposition (O : Set ι) [DecidablePred (· ∈ O)] + (q : ι) (x : ι → ZMod 2) (hx : observedPart O x = 0) : + x = extendUnread (insert q O) (unreadPart (insert q O) x) + x q • Pi.single q 1 := by + funext i + by_cases hi : i = q + · subst i + simp [extendUnread, Pi.smul_apply] + · by_cases hO : i ∈ O + · have hx0 : x i = 0 := congrFun hx ⟨i, hO⟩ + simp [extendUnread, unreadPart, Pi.smul_apply, hi, hO, hx0] + · simp [extendUnread, unreadPart, Pi.smul_apply, hi, hO] + +/-- A single unread column belongs to the unread image. -/ +theorem column_mem_unreadRange + (D : (ι → ZMod 2) →ₗ[ZMod 2] (Fin r → ZMod 2)) + (O : Set ι) [DecidablePred (· ∈ O)] (q : ι) (hq : q ∉ O) : + column D q ∈ LinearMap.range (unreadMap D O) := by + refine ⟨unreadPart O (Pi.single q 1), ?_⟩ + change D (extendUnread O (unreadPart O (Pi.single q 1))) = D (Pi.single q 1) + congr 1 + apply extendUnread_unreadPart_of_observed_zero + funext i + have hi : i.val ≠ q := by intro h; exact hq (h ▸ i.property) + simp [observedPart, hi] + +/-- Adding the queried unread column to the other unread image recovers the current image. -/ +theorem unreadRange_eq_withColumn + (D : (ι → ZMod 2) →ₗ[ZMod 2] (Fin r → ZMod 2)) + (O : Set ι) [DecidablePred (· ∈ O)] (q : ι) (hq : q ∉ O) : + LinearMap.range (unreadMap D O) = + Affine.withColumn (unreadMap D (insert q O)) (column D q) := by + apply le_antisymm + · rintro y ⟨u, rfl⟩ + let x := extendUnread O u + have hx : observedPart O x = 0 := by + funext i + simp [x, observedPart, extendUnread, i.property] + have he := congrArg D (unread_insert_decomposition O q x hx) + simp only [map_add, map_smul] at he + change D x ∈ LinearMap.range (unreadMap D (insert q O)) ⊔ + Submodule.span (ZMod 2) {column D q} + apply Submodule.mem_sup.mpr + refine ⟨unreadMap D (insert q O) (unreadPart (insert q O) x), + LinearMap.mem_range_self _ _, x q • column D q, ?_, he.symm⟩ + exact Submodule.smul_mem _ _ (Submodule.subset_span (by simp)) + · apply sup_le + · exact unreadMap_range_antitone D (Set.subset_insert q O) + · exact Submodule.span_le.mpr (by + intro c hc + rcases Set.mem_singleton_iff.mp hc with rfl + exact column_mem_unreadRange D O q hq) + +/-- A column is redundant exactly when a kernel vector flips it and leaves observed +coordinates fixed. The resulting translation will preserve the conditioned input law. -/ +theorem column_mem_iff_kernel_vector + (D : (ι → ZMod 2) →ₗ[ZMod 2] (Fin r → ZMod 2)) + (O : Set ι) [DecidablePred (· ∈ O)] (q : ι) (hq : q ∉ O) : + column D q ∈ LinearMap.range (unreadMap D (insert q O)) ↔ + ∃ k : ι → ZMod 2, observedPart O k = 0 ∧ D k = 0 ∧ k q = 1 := by + constructor + · rintro ⟨u, hu⟩ + refine ⟨Pi.single q 1 - extendUnread (insert q O) u, ?_, ?_, ?_⟩ + · funext i + have hi : i.val ≠ q := by intro h; exact hq (h ▸ i.property) + simp [observedPart, extendUnread, hi, i.property] + · change D (Pi.single q 1 - extendUnread (insert q O) u) = 0 + rw [map_sub] + exact sub_eq_zero.mpr hu.symm + · simp [extendUnread] + · rintro ⟨k, hkO, hkD, hkq⟩ + have he := congrArg D (unread_insert_decomposition O q k hkO) + simp only [map_add, hkD, hkq, one_smul] at he + have hneg : unreadMap D (insert q O) (unreadPart (insert q O) k) = -column D q := by + apply eq_neg_of_add_eq_zero_left + exact he.symm + refine ⟨-unreadPart (insert q O) k, ?_⟩ + rw [map_neg, hneg, neg_neg] + +/-- Deleting the queried unread column strictly lowers numerical rank exactly when +that column is not in the span of the other unread columns. -/ +theorem rank_drop_iff_column_not_mem + (D : (ι → ZMod 2) →ₗ[ZMod 2] (Fin r → ZMod 2)) + (O : Set ι) [DecidablePred (· ∈ O)] (q : ι) (hq : q ∉ O) : + Module.finrank (ZMod 2) (LinearMap.range (unreadMap D (insert q O))) < + Module.finrank (ZMod 2) (LinearMap.range (unreadMap D O)) ↔ + column D q ∉ LinearMap.range (unreadMap D (insert q O)) := by + rw [unreadRange_eq_withColumn D O q hq] + exact Affine.rank_drop_iff_not_mem_range _ _ + +/-- If the queried column is not redundant, any two compatible assignments with +the same observed values must have the same next answer. -/ +theorem answer_eq_of_column_not_mem + (D : (ι → ZMod 2) →ₗ[ZMod 2] (Fin r → ZMod 2)) + (O : Set ι) [DecidablePred (· ∈ O)] (q : ι) (hq : q ∉ O) + (hc : column D q ∉ LinearMap.range (unreadMap D (insert q O))) + {x y : ι → ZMod 2} (hO : observedPart O x = observedPart O y) (hD : D x = D y) : + x q = y q := by + by_contra hqxy + apply hc + apply (column_mem_iff_kernel_vector D O q hq).mpr + refine ⟨(x q - y q)⁻¹ • (x - y), ?_, ?_, ?_⟩ + · funext i + have hi : x i.val = y i.val := congrFun hO i + simp [observedPart, Pi.smul_apply, hi] + · simp [map_smul, map_sub, hD] + · simp [Pi.smul_apply, smul_eq_mul, sub_ne_zero.mpr hqxy] + +end Klr.AffineAnswer diff --git a/LeanPool/KLRandomness/AffineAnswerMeasure.lean b/LeanPool/KLRandomness/AffineAnswerMeasure.lean new file mode 100644 index 0000000000..2a5c39545c --- /dev/null +++ b/LeanPool/KLRandomness/AffineAnswerMeasure.lean @@ -0,0 +1,154 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.RemainingRank +import Mathlib.Tactic.NormNum + +/-! +# Fair-coin translations and conditional answer probabilities + +Adding a fixed binary-field sequence to the input preserves the concrete +infinite-product fair-coin measure. If such a translation preserves a +conditioning event and flips a queried coordinate, the conditional answer is +fair. This supplies the measure step for affine kernel translations. +-/ + +@[expose] public section + +namespace Klr.AffineAnswer + +open MeasureTheory ProbabilityTheory FiniteMeasure +open scoped ENNReal + +/-- Translate a bit by an element of the binary field. -/ +def translateBit (a : ZMod 2) : Bool ≃ Bool where + toFun b := boolEquivF2.symm (boolEquivF2 b + a) + invFun b := boolEquivF2.symm (boolEquivF2 b - a) + left_inv b := by simp + right_inv b := by simp + +@[simp] theorem boolEquivF2_translateBit (a : ZMod 2) (b : Bool) : + boolEquivF2 (translateBit a b) = boolEquivF2 b + a := by + simp [translateBit] + +@[simp] theorem translateBit_zero (b : Bool) : translateBit 0 b = b := by + simp [translateBit] + +@[simp] theorem translateBit_one (b : Bool) : translateBit 1 b = !b := by + cases b <;> apply boolEquivF2.injective <;> norm_num + exact ZMod.natCast_self 2 + +/-- Coordinatewise translation by a fixed binary-field sequence. -/ +def translate (z : ℕ → ZMod 2) (X : Cantor) : Cantor := + fun n => translateBit (z n) (X n) + +theorem measurable_translate (z : ℕ → ZMod 2) : Measurable (translate z) := by + apply Measurable.of_eval + intro n + exact (Measurable.of_discrete (f := translateBit (z n))).comp (measurable_pi_apply n) + +theorem fairBit_map_translateBit (a : ZMod 2) : fairBit.map (translateBit a) = fairBit := by + apply Measure.ext_of_singleton + intro b + rw [Measure.map_apply (Measurable.of_discrete (f := translateBit a)) + (measurableSet_singleton b)] + have he : (translateBit a) ⁻¹' {b} = {(translateBit a).symm b} := by + ext x + change translateBit a x = b ↔ x = (translateBit a).symm b + exact (translateBit a).eq_symm_apply.symm + rw [he, fairBit_singleton, fairBit_singleton] + +/-- Translation invariance of the actual infinite-product fair-coin measure. -/ +theorem fairCoin_map_translate (z : ℕ → ZMod 2) : + fairCoin.map (translate z) = fairCoin := by + unfold fairCoin translate + rw [Measure.infinitePi_map_pi (fun _ : ℕ => fairBit) + (fun n => Measurable.of_discrete (f := translateBit (z n)))] + simp only [fairBit_map_translateBit] + +/-- A translation vanishing on an event's supporting coordinates preserves that event. -/ +theorem translate_mem_of_dependsOn (H : Set Cantor) (S : Set ℕ) + (hH : DependsOn (fun X : Cantor => X ∈ H) S) (z : ℕ → ZMod 2) + (hz : ∀ n ∈ S, z n = 0) (X : Cantor) : translate z X ∈ H ↔ X ∈ H := by + apply iff_of_eq + apply hH + intro n hn + simp [translate, hz n hn] + +/-- One specified input bit. -/ +def bitEvent (q : ℕ) (b : Bool) : Set Cantor := {X | X q = b} + +theorem measurableSet_bitEvent (q : ℕ) (b : Bool) : MeasurableSet (bitEvent q b) := by + change MeasurableSet ((fun X : Cantor => X q) ⁻¹' ({b} : Set Bool)) + exact (measurable_pi_apply q) (measurableSet_singleton b) + +/-- A translation preserving a history and flipping its next bit equates the two +answer probabilities, even for a null history. -/ +theorem fairCoin_inter_bit_eq_of_translation (H : Set Cantor) (hH : MeasurableSet H) + (z : ℕ → ZMod 2) (hinv : ∀ X, translate z X ∈ H ↔ X ∈ H) + (q : ℕ) (hz : z q = 1) : + fairCoin (H ∩ bitEvent q false) = fairCoin (H ∩ bitEvent q true) := by + have he : translate z ⁻¹' (H ∩ bitEvent q true) = H ∩ bitEvent q false := by + ext X + simp [hinv, bitEvent, translate, hz] + calc + fairCoin (H ∩ bitEvent q false) = + fairCoin (translate z ⁻¹' (H ∩ bitEvent q true)) := by rw [he] + _ = (fairCoin.map (translate z)) (H ∩ bitEvent q true) := + (Measure.map_apply (measurable_translate z) (hH.inter (measurableSet_bitEvent q true))).symm + _ = _ := by rw [fairCoin_map_translate] + +/-- A symmetry interchanging the two answers makes the conditional next bit fair. +The explicit nonnull hypothesis is precisely compatibility of this history. -/ +theorem cond_bit_eq_half_of_translation (H : Set Cantor) (hH : MeasurableSet H) + (hpos : fairCoin H ≠ 0) (z : ℕ → ZMod 2) + (hinv : ∀ X, translate z X ∈ H ↔ X ∈ H) (q : ℕ) (hz : z q = 1) (b : Bool) : + (cond fairCoin H) (bitEvent q b) = (1 / 2 : ℝ≥0∞) := by + have heq := fairCoin_inter_bit_eq_of_translation H hH z hinv q hz + have hdis : Disjoint (H ∩ bitEvent q false) (H ∩ bitEvent q true) := by + apply Set.disjoint_left.mpr + intro X hx hy + exact Bool.false_ne_true (hx.2.symm.trans hy.2) + have hunion : (H ∩ bitEvent q false) ∪ (H ∩ bitEvent q true) = H := by + ext X + cases hb : X q <;> simp [bitEvent, hb] + have hsum : fairCoin H = fairCoin (H ∩ bitEvent q false) + + fairCoin (H ∩ bitEvent q true) := by + calc + fairCoin H = fairCoin ((H ∩ bitEvent q false) ∪ (H ∩ bitEvent q true)) := by + rw [hunion] + _ = _ := measure_union hdis (hH.inter (measurableSet_bitEvent q true)) + have htwo : (1 / 2 : ℝ≥0∞) * 2 = 1 := by + rw [one_div, ENNReal.inv_mul_cancel (by norm_num) (by norm_num)] + have hhalf (a : Bool) : fairCoin (H ∩ bitEvent q a) = + (1 / 2 : ℝ≥0∞) * fairCoin H := by + cases a + · rw [hsum, ← heq, ← two_mul, ← mul_assoc, htwo, one_mul] + · rw [← heq, hsum, ← heq, ← two_mul, ← mul_assoc, htwo, one_mul] + rw [cond_apply hH, hhalf, mul_left_comm, + ENNReal.inv_mul_cancel hpos (measure_ne_top _ _), mul_one] + +/-- If a compatible history determines the bit, its conditional probability is one, +and the probability of the opposite bit is zero. -/ +theorem cond_bit_eq_one_zero_of_subset (H : Set Cantor) (hH : MeasurableSet H) + (hpos : fairCoin H ≠ 0) (q : ℕ) (b : Bool) (hsub : H ⊆ bitEvent q b) : + (cond fairCoin H) (bitEvent q b) = 1 ∧ + (cond fairCoin H) (bitEvent q (!b)) = 0 := by + constructor + · rw [cond_apply hH, Set.inter_eq_left.mpr hsub, + ENNReal.inv_mul_cancel hpos (measure_ne_top _ _)] + · have he : H ∩ bitEvent q (!b) = ∅ := by + apply Set.eq_empty_iff_forall_notMem.mpr + intro X hX + have hb := (hsub hX.1).symm.trans hX.2 + cases b <;> cases hb + rw [cond_apply hH, he, measure_empty, mul_zero] + +end Klr.AffineAnswer diff --git a/LeanPool/KLRandomness/AffineBlock.lean b/LeanPool/KLRandomness/AffineBlock.lean new file mode 100644 index 0000000000..dd62c006b8 --- /dev/null +++ b/LeanPool/KLRandomness/AffineBlock.lean @@ -0,0 +1,243 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.FiniteStage +import Mathlib.Tactic.NormNum + +/-! +# Disjoint affine blocks and finite-stage laws + +This module instantiates the finite-coordinate identity with actual finite sets +of input positions. The ambient coordinates, the old-event representation and +the transcript's coordinate witnesses are constructed in the proof, rather +than left as hypotheses of the block theorem. +-/ + +@[expose] public section + +namespace Klr + +open MeasureTheory ProbabilityTheory +open AffineObservation FiniteMeasure FiniteStage +open scoped ENNReal + +namespace ScanRule + +/-- The input positions queried along a prescribed finite transcript. -/ +def queriedPositions (π : ScanRule) (v : List Bool) : Finset ℕ := + Finset.univ.image (fun i : Fin v.length => π.query (v.take i.val)) + +theorem query_mem_queriedPositions (π : ScanRule) (v : List Bool) (i : Fin v.length) : + π.query (v.take i.val) ∈ π.queriedPositions v := by + exact Finset.mem_image.mpr ⟨i, Finset.mem_univ _, rfl⟩ + +@[simp] theorem queriedPositions_nil (π : ScanRule) : π.queriedPositions [] = ∅ := by + simp [queriedPositions] + +end ScanRule + +/-- A finite full-row-rank system of parity equations and its chosen syndrome. -/ +structure AffineBlock where + /-- Coordinates constrained by the affine equations. -/ + support : Finset ℕ + /-- Number of independent parity equations. -/ + rank : ℕ + /-- Surjective linear map defining the parity equations on the support. -/ + matrix : (support → ZMod 2) →ₗ[ZMod 2] (Fin rank → ZMod 2) + fullRank : Function.Surjective matrix + /-- Right-hand side of the parity equations. -/ + syndrome : Fin rank → ZMod 2 + +namespace AffineBlock + +/-- The input event satisfying a block's parity equations. -/ +def event (B : AffineBlock) : Set Cantor := + affineEvent (fun i : B.support => i.val) B.matrix B.syndrome + +theorem measurableSet_event (B : AffineBlock) : MeasurableSet B.event := + measurableSet_affineEvent _ _ _ + +theorem dependsOn_event (B : AffineBlock) : + DependsOn (fun X : Cantor => X ∈ B.event) (B.support : Set ℕ) := by + intro X Y h + have hv : coordinateValues (fun i : B.support => i.val) X = + coordinateValues (fun i : B.support => i.val) Y := by + funext i + rw [coordinateValues_apply, coordinateValues_apply, h i.val i.property] + change (B.matrix (coordinateValues _ X) = B.syndrome) = + (B.matrix (coordinateValues _ Y) = B.syndrome) + rw [hv] + +/-- The columns already read along the fixed transcript. -/ +def observed (B : AffineBlock) (π : ScanRule) (v : List Bool) : Set B.support := + {i | i.val ∈ π.queriedPositions v} + +instance (B : AffineBlock) (π : ScanRule) (v : List Bool) : + DecidablePred (· ∈ B.observed π v) := + fun i => inferInstanceAs (Decidable (i.val ∈ π.queriedPositions v)) + +/-- Full row rank of the columns still unread after this transcript. -/ +def UnreadFullRank (B : AffineBlock) (π : ScanRule) (v : List Bool) : Prop := + Function.Surjective (unreadMap B.matrix (B.observed π v)) + +theorem unreadFullRank_nil (B : AffineBlock) (π : ScanRule) : + B.UnreadFullRank π [] := by + intro y + obtain ⟨x, hx⟩ := B.fullRank y + refine ⟨fun i => x i.val, ?_⟩ + change B.matrix (extendUnread (B.observed π []) (fun i => x i.val)) = y + have he : extendUnread (B.observed π []) (fun i => x i.val) = x := by + funext i + change (if h : i ∈ B.observed π [] then 0 else x i) = x i + simp [observed] + rw [he, hx] + +/-- Restriction from a larger finite ambient set to a block's coordinates. -/ +def restrictCoordinates {S G : Finset ℕ} (h : S ⊆ G) : + (G → ZMod 2) →ₗ[ZMod 2] (S → ZMod 2) where + toFun x i := x ⟨i.val, h i.property⟩ + map_add' _ _ := rfl + map_smul' _ _ := rfl + +/-- Extend a finite assignment by zero outside its support. -/ +def extendCoordinates {S : Finset ℕ} (G : Finset ℕ) (x : S → ZMod 2) : + G → ZMod 2 := fun i => if h : i.val ∈ S then x ⟨i.val, h⟩ else 0 + +@[simp] theorem restrict_extendCoordinates {S G : Finset ℕ} (h : S ⊆ G) + (x : S → ZMod 2) : restrictCoordinates h (extendCoordinates G x) = x := by + funext i + simp [restrictCoordinates, extendCoordinates, i.property] + +/-- An arbitrary earlier event on disjoint finite support satisfies the exact stage identity. +The full-rank hypothesis is solely about the new block's unread columns. -/ +theorem finiteStage_identity_of_dependsOn (B : AffineBlock) (A : Set Cantor) + (H : Finset ℕ) (hA : DependsOn (fun X : Cantor => X ∈ A) (H : Set ℕ)) + (hdis : Disjoint H B.support) (π : ScanRule) (v : List Bool) + (hfull : B.UnreadFullRank π v) : + (cond fairCoin A) ({X | π.transcript X v.length = v} ∩ B.event) = + (1 / 2 : ℝ≥0∞) ^ B.rank * + (cond fairCoin A) {X | π.transcript X v.length = v} := by + classical + let G := H ∪ B.support ∪ π.queriedPositions v + have hH : H ⊆ G := by intro n hn; simp [G, hn] + have hS : B.support ⊆ G := by intro n hn; simp [G, hn] + have hQ : π.queriedPositions v ⊆ G := by intro n hn; simp [G, hn] + let e : G → ℕ := Subtype.val + let O : Set G := {i | i.val ∉ B.support ∨ i.val ∈ π.queriedPositions v} + let D := B.matrix.comp (restrictCoordinates hS) + let L (u : {i : B.support // i ∉ B.observed π v} → ZMod 2) : G → ZMod 2 := + extendCoordinates G (extendUnread (B.observed π v) u) + have hzero : ∀ u, observedPart O (L u) = 0 := by + intro u + funext i + rcases i.property with hi | hi + · simp [observedPart, L, extendCoordinates, hi] + · by_cases hs : i.val.val ∈ B.support + · simp only [observedPart, L, extendCoordinates, dite_eq_left hs] + change (if h : i.val.val ∈ π.queriedPositions v then 0 + else u ⟨⟨i.val.val, hs⟩, h⟩) = 0 + rw [dite_eq_left hi] + · simp [observedPart, L, extendCoordinates, hs] + have hsurj : Function.Surjective (fun u => D (L u)) := by + intro y + obtain ⟨u, hu⟩ := hfull y + refine ⟨u, ?_⟩ + simpa [D, L, unreadMap, LinearMap.comp_apply] using hu + have hD := unreadMap_surjective_of_supported_lift D O L hzero hsurj + have hdep : DependsOn (fun X : Cantor => X ∈ A) (e '' O) := by + apply hA.mono + intro n hn + exact ⟨⟨n, hH hn⟩, Or.inl (Finset.disjoint_left.mp hdis hn), rfl⟩ + obtain ⟨P, hP⟩ := exists_observedEvent_of_dependsOn e O A hdep + let q : Fin v.length → O := fun i => + ⟨⟨π.query (v.take i.val), hQ (π.query_mem_queriedPositions v i)⟩, + Or.inr (π.query_mem_queriedPositions v i)⟩ + have hq : ∀ i, e (q i).val = π.query (v.take i.val) := fun _ => rfl + have h := cond_transcript_inter_affine e Subtype.val_injective D O P π v q hq + B.syndrome hD + rw [← hP] at h + exact h + +/-- The common support of finitely many earlier blocks. -/ +def familySupport {κ : Type*} [Fintype κ] (B : κ → AffineBlock) : Finset ℕ := + Finset.univ.biUnion (fun k => (B k).support) + +/-- The conjunction of all earlier block constraints. -/ +def familyEvent {κ : Type*} (B : κ → AffineBlock) : Set Cantor := + {X | ∀ k, X ∈ (B k).event} + +theorem measurableSet_familyEvent {κ : Type*} [Countable κ] (B : κ → AffineBlock) : + MeasurableSet (familyEvent B) := by + have he : familyEvent B = ⋂ k, (B k).event := by + ext X + simp [familyEvent] + rw [he] + exact MeasurableSet.iInter (fun k => (B k).measurableSet_event) + +theorem familyEvent_dependsOn {κ : Type*} [Fintype κ] (B : κ → AffineBlock) : + DependsOn (fun X : Cantor => X ∈ familyEvent B) (familySupport B : Set ℕ) := by + intro X Y h + apply propext + change (∀ k, X ∈ (B k).event) ↔ (∀ k, Y ∈ (B k).event) + have he (k : κ) : (X ∈ (B k).event) = (Y ∈ (B k).event) := by + apply (B k).dependsOn_event + intro n hn + apply h n + exact Finset.mem_biUnion.mpr ⟨k, Finset.mem_univ _, hn⟩ + simp_rw [he] + +/-- The actual finite-stage law, obtained by conditioning fair coin on the earlier blocks. -/ +noncomputable def finiteStageLaw {κ : Type*} (B : κ → AffineBlock) : Measure Cantor := + cond fairCoin (familyEvent B) + +/-- The paper's stage identity for an explicit finite family of old constraints and a new +disjoint block. It includes null transcript events without an extra case assumption. -/ +theorem finiteStage_identity {κ : Type*} [Finite κ] (old : κ → AffineBlock) + (B : AffineBlock) (hdis : ∀ k, Disjoint (old k).support B.support) + (π : ScanRule) (v : List Bool) (hfull : B.UnreadFullRank π v) : + (finiteStageLaw old) ({X | π.transcript X v.length = v} ∩ B.event) = + (1 / 2 : ℝ≥0∞) ^ B.rank * + (finiteStageLaw old) {X | π.transcript X v.length = v} := by + let _ := Fintype.ofFinite κ + apply B.finiteStage_identity_of_dependsOn (familyEvent old) (familySupport old) + (familyEvent_dependsOn old) _ π v hfull + rw [Finset.disjoint_left] + intro n hn hb + obtain ⟨k, _, hk⟩ := Finset.mem_biUnion.mp hn + exact Finset.disjoint_left.mp (hdis k) hk hb + +/-- A nonnull earlier background makes the finite-stage law a probability measure. -/ +theorem finiteStageLaw_isProbabilityMeasure {κ : Type*} (old : κ → AffineBlock) + (h : fairCoin (familyEvent old) ≠ 0) : IsProbabilityMeasure (finiteStageLaw old) := + cond_isProbabilityMeasure h + +/-- Before any new bit is read, each syndrome of a disjoint new block has its uniform mass. -/ +theorem finiteStageLaw_event {κ : Type*} [Finite κ] (old : κ → AffineBlock) + (B : AffineBlock) (hdis : ∀ k, Disjoint (old k).support B.support) + (hold : fairCoin (familyEvent old) ≠ 0) : + (finiteStageLaw old) B.event = (1 / 2 : ℝ≥0∞) ^ B.rank := by + let _ := finiteStageLaw_isProbabilityMeasure old hold + simpa using finiteStage_identity old B hdis ScanRule.monotone [] + (B.unreadFullRank_nil ScanRule.monotone) + +/-- A full-row-rank block has exactly the expected fair-coin probability. -/ +theorem fairCoin_event (B : AffineBlock) : + fairCoin B.event = (1 / 2 : ℝ≥0∞) ^ B.rank := by + have h := B.finiteStage_identity_of_dependsOn Set.univ ∅ (by + intro X Y _ + rfl) (by simp) ScanRule.monotone [] (B.unreadFullRank_nil ScanRule.monotone) + simpa using h + +theorem fairCoin_event_ne_zero (B : AffineBlock) : fairCoin B.event ≠ 0 := by + rw [fairCoin_event] + exact pow_ne_zero _ (by norm_num) + +end AffineBlock +end Klr diff --git a/LeanPool/KLRandomness/AffineCode.lean b/LeanPool/KLRandomness/AffineCode.lean new file mode 100644 index 0000000000..fe1f4fe99a --- /dev/null +++ b/LeanPool/KLRandomness/AffineCode.lean @@ -0,0 +1,237 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.EffectiveScan +public import LeanPool.KLRandomness.FiniteStage +public import Mathlib.LinearAlgebra.Matrix.ToLin +import Mathlib.Tactic.NormNum + +/-! +# Effective finite affine-system codes + +A code gives a width, a row count, Boolean matrix rows, a syndrome, and Boolean +rows of a right-inverse certificate. Missing entries are zero. +A finite Boolean computation checks `A * R = 1`, which proves +full row rank. Equations use the initial input segment; arbitrary finite +supports are represented by inserting zero columns. +-/ + +@[expose] public section + +namespace Klr.AffineCode + +open FiniteMeasure MeasureTheory +open scoped ENNReal + +/-- An encoding of a binary matrix with its dimensions, syndrome and right inverse. -/ +abbrev Data := (ℕ × ℕ) × (List (List Bool) × (List Bool × List (List Bool))) + +/-- Number of columns in the encoded parity matrix. -/ +def width (c : Data) : ℕ := c.1.1 +/-- Rows of the encoded parity matrix. -/ +def rows (c : Data) : List (List Bool) := c.2.1 +/-- Right-hand side of the encoded affine system. -/ +def syndrome (c : Data) : List Bool := c.2.2.1 +/-- Rows of the encoded candidate right inverse. -/ +def certificate (c : Data) : List (List Bool) := c.2.2.2 +/-- Number of equations claimed to be independent by the certificate. -/ +def rank (c : Data) : ℕ := c.1.2 + +/-- Matrix entry with zero returned outside the encoded rows or columns. -/ +def entry (a : List (List Bool)) (i j : ℕ) : Bool := (a.getD i []).getD j false + +/-- Exclusive-or of the first `n` Boolean values. -/ +def parity (p : ℕ → Bool) : ℕ → Bool + | 0 => false + | n + 1 => Bool.xor (parity p n) (p n) + +theorem value_xor (a b : Bool) : + boolEquivF2 (Bool.xor a b) = boolEquivF2 a + boolEquivF2 b := by + cases a <;> cases b <;> decide + +theorem value_and (a b : Bool) : + boolEquivF2 (a && b) = boolEquivF2 a * boolEquivF2 b := by + cases a <;> cases b <;> simp + +theorem value_parity (p : ℕ → Bool) (n : ℕ) : + boolEquivF2 (parity p n) = ∑ i : Fin n, boolEquivF2 (p i.val) := by + induction n with + | zero => simp [parity] + | succ n ih => + rw [parity, value_xor, ih, Fin.sum_univ_castSucc] + rfl + +theorem computable_parity {α : Type*} [Primcodable α] {p : α → ℕ → Bool} + (hp : Computable₂ p) : Computable (fun a : α × ℕ => parity (p a.1) a.2) := by + have hs : Computable₂ (fun (a : α × ℕ) (b : ℕ × Bool) => Bool.xor b.2 (p a.1 b.1)) := + ((Primrec.dom_bool₂ Bool.xor).to_comp.comp (Computable.snd.comp Computable.snd) + (hp.comp (Computable.fst.comp Computable.fst) + (Computable.fst.comp Computable.snd))).to₂ + apply (Computable.nat_rec Computable.snd (Computable.const false) hs).of_eq + intro a + induction a.2 with + | zero => rfl + | succ n ih => + simpa only [parity, Nat.rec_add_one] using congrArg (fun b => Bool.xor b (p a.1 n)) ih + +theorem computable_entry : + Computable (fun p : List (List Bool) × (ℕ × ℕ) => entry p.1 p.2.1 p.2.2) := by + have hr := (Primrec.list_getD ([] : List Bool)).to_comp.comp + (Computable.fst : Computable (fun p : List (List Bool) × (ℕ × ℕ) => p.1)) + (Computable.fst.comp Computable.snd) + have hc := (Primrec.list_getD false).to_comp.comp hr (Computable.snd.comp Computable.snd) + exact hc.of_eq fun _ => rfl + +theorem computable_width : Computable width := Computable.fst.comp Computable.fst +theorem computable_rows : Computable rows := Computable.fst.comp Computable.snd +theorem computable_syndrome : Computable syndrome := + Computable.fst.comp (Computable.snd.comp Computable.snd) +theorem computable_certificate : Computable certificate := + Computable.snd.comp (Computable.snd.comp Computable.snd) +theorem computable_rank : Computable rank := Computable.snd.comp Computable.fst + +/-- Entry of the encoded product of the matrix and its right-inverse certificate. -/ +def productEntry (c : Data) (i j : ℕ) : Bool := + parity (fun k => entry (rows c) i k && entry (certificate c) k j) (width c) + +theorem computable_productEntry : + Computable (fun p : Data × (ℕ × ℕ) => productEntry p.1 p.2.1 p.2.2) := by + have ha : Computable (fun p : (Data × (ℕ × ℕ)) × ℕ => + entry (rows p.1.1) p.1.2.1 p.2) := by + have hd : Computable (fun p : (Data × (ℕ × ℕ)) × ℕ => p.1.1) := + Computable.fst.comp Computable.fst + have hi : Computable (fun p : (Data × (ℕ × ℕ)) × ℕ => p.1.2.1) := + Computable.fst.comp (Computable.snd.comp Computable.fst) + have hk : Computable (fun p : (Data × (ℕ × ℕ)) × ℕ => p.2) := Computable.snd + have hc := computable_entry.comp ((computable_rows.comp hd).pair (hi.pair hk)) + exact hc.of_eq fun _ => rfl + have hb : Computable (fun p : (Data × (ℕ × ℕ)) × ℕ => + entry (certificate p.1.1) p.2 p.1.2.2) := by + have hd : Computable (fun p : (Data × (ℕ × ℕ)) × ℕ => p.1.1) := + Computable.fst.comp Computable.fst + have hj : Computable (fun p : (Data × (ℕ × ℕ)) × ℕ => p.1.2.2) := + Computable.snd.comp (Computable.snd.comp Computable.fst) + have hk : Computable (fun p : (Data × (ℕ × ℕ)) × ℕ => p.2) := Computable.snd + have hc := computable_entry.comp ((computable_certificate.comp hd).pair (hk.pair hj)) + exact hc.of_eq fun _ => rfl + have hp := Primrec.and.to_comp.comp ha hb + have hw : Computable (fun p : Data × (ℕ × ℕ) => width p.1) := + computable_width.comp Computable.fst + have hc := (computable_parity (p := fun p : Data × (ℕ × ℕ) => fun k => + entry (rows p.1) p.2.1 k && entry (certificate p.1) k p.2.2) hp).comp + (Computable.id.pair hw) + exact hc.of_eq fun _ => rfl + +/-- Finite verification of a supplied right inverse. -/ +def valid (c : Data) : Bool := + EffectiveScan.boundedAll (fun i => EffectiveScan.boundedAll + (fun j => decide (productEntry c i j = decide (i = j))) (rank c)) (rank c) + +theorem valid_eq_true (c : Data) : valid c = true ↔ + ∀ i < rank c, ∀ j < rank c, productEntry c i j = decide (i = j) := by + simp only [valid, EffectiveScan.boundedAll_eq_true, decide_eq_true_eq] + +theorem computable_valid : Computable valid := by + have hp : Computable (fun p : (Data × ℕ) × ℕ => + decide (productEntry p.1.1 p.1.2 p.2 = decide (p.1.2 = p.2))) := by + have hd : Computable (fun p : (Data × ℕ) × ℕ => p.1.1) := + Computable.fst.comp Computable.fst + have hrow : Computable (fun p : (Data × ℕ) × ℕ => p.1.2) := + Computable.snd.comp Computable.fst + have hcol : Computable (fun p : (Data × ℕ) × ℕ => p.2) := Computable.snd + have he := computable_productEntry.comp (hd.pair (hrow.pair hcol)) + have hi := Primrec.eq.decide.to_comp.comp hrow hcol + have hc := Primrec.eq.decide.to_comp.comp he hi + exact hc.of_eq fun _ => rfl + have hr : Computable (fun p : Data × ℕ => rank p.1) := + computable_rank.comp Computable.fst + have inner := (EffectiveScan.computable_boundedAll + (p := fun p : Data × ℕ => fun j => + decide (productEntry p.1 p.2 j = decide (p.2 = j))) hp).comp (Computable.id.pair hr) + have hc := (EffectiveScan.computable_boundedAll + (p := fun c : Data => fun i => EffectiveScan.boundedAll + (fun j => decide (productEntry c i j = decide (i = j))) (rank c)) inner).comp + (Computable.id.pair computable_rank) + exact hc.of_eq fun _ => rfl + +/-- Parity matrix over the two-element field read from the code. -/ +def matrix (c : Data) : Matrix (Fin (rank c)) (Fin (width c)) (ZMod 2) := + fun i j => boolEquivF2 (entry (rows c) i.val j.val) + +/-- Candidate right inverse over the two-element field read from the code. -/ +def rightMatrix (c : Data) : Matrix (Fin (width c)) (Fin (rank c)) (ZMod 2) := + fun i j => boolEquivF2 (entry (certificate c) i.val j.val) + +/-- Encoded syndrome interpreted as a vector over the two-element field. -/ +def syndromeVector (c : Data) : Fin (rank c) → ZMod 2 := + fun i => boolEquivF2 ((syndrome c).getD i.val false) + +theorem value_productEntry (c : Data) (i j : Fin (rank c)) : + boolEquivF2 (productEntry c i.val j.val) = (matrix c * rightMatrix c) i j := by + simp only [productEntry, value_parity, value_and, Matrix.mul_apply, matrix, rightMatrix] + +theorem valid_iff_right_inverse (c : Data) : + valid c = true ↔ matrix c * rightMatrix c = 1 := by + rw [valid_eq_true] + constructor + · intro h + ext i j + rw [← value_productEntry, h i.val i.isLt j.val j.isLt] + by_cases he : i = j + · subst j + simp + · have hv : i.val ≠ j.val := fun h => he (Fin.ext h) + simp [hv, he] + · intro h i hi j hj + apply boolEquivF2.injective + rw [value_productEntry c ⟨i, hi⟩ ⟨j, hj⟩, h] + by_cases he : i = j + · subst j + simp + · simp [he, Fin.ext_iff] + +theorem surjective_of_valid (c : Data) (hc : valid c = true) : + Function.Surjective (matrix c).mulVecLin := by + intro y + refine ⟨Matrix.mulVec (rightMatrix c) y, ?_⟩ + rw [Matrix.mulVecLin_apply, Matrix.mulVec_mulVec, (valid_iff_right_inverse c).mp hc, + Matrix.one_mulVec] + +/-- The actual finite affine event decoded from this system. -/ +def event (c : Data) : Set Cantor := + FiniteStage.affineEvent (fun i : Fin (width c) => i.val) (matrix c).mulVecLin (syndromeVector c) + +theorem measurableSet_event (c : Data) : MeasurableSet (event c) := + FiniteStage.measurableSet_affineEvent _ _ _ + +/-- The verified rank determines the exact measure of every decoded syndrome event. -/ +theorem fairCoin_event (c : Data) (hc : valid c = true) : + fairCoin (event c) = (1 / 2 : ℝ≥0∞) ^ rank c := by + have hs := surjective_of_valid c hc + have hd := (matrix c).mulVecLin.finrank_range_add_finrank_ker + rw [LinearMap.range_eq_top.mpr hs, finrank_top] at hd + simp only [Module.finrank_pi, Fintype.card_fin] at hd + have hr : rank c ≤ width c := by omega + change fairCoin {X | coordinateValues (fun i : Fin (width c) => i.val) X ∈ + {x | (matrix c).mulVecLin x = syndromeVector c}} = _ + rw [fairCoin_coordinate_event_f2 _ Fin.val_injective] + simp only [Fintype.card_fin] + change (Nat.card (Affine.Fiber (matrix c).mulVecLin (syndromeVector c)) : ℝ≥0∞) * _ = _ + rw [Affine.card_binary_fiber _ hs, Nat.cast_pow, Nat.cast_ofNat] + have hp : (1 / 2 : ℝ≥0∞) ^ width c = + (1 / 2 : ℝ≥0∞) ^ (width c - rank c) * (1 / 2 : ℝ≥0∞) ^ rank c := by + rw [← pow_add, Nat.sub_add_cancel hr] + rw [hp, ← mul_assoc, ← mul_pow] + have htwo : (2 : ℝ≥0∞) * (1 / 2) = 1 := by + simpa only [one_div] using ENNReal.mul_inv_cancel + (by norm_num : (2 : ℝ≥0∞) ≠ 0) (by norm_num : (2 : ℝ≥0∞) ≠ ∞) + rw [htwo, one_pow, one_mul] + +end Klr.AffineCode diff --git a/LeanPool/KLRandomness/AffineCodeCoverage.lean b/LeanPool/KLRandomness/AffineCodeCoverage.lean new file mode 100644 index 0000000000..c1c2216192 --- /dev/null +++ b/LeanPool/KLRandomness/AffineCodeCoverage.lean @@ -0,0 +1,142 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.AffineCode +public import LeanPool.KLRandomness.AffineBlock +public import Mathlib.Data.List.OfFn + +/-! +# Coverage of full-row-rank affine systems + +Every surjective finite binary matrix has a right inverse, so supplying a +certificate imposes no restriction on the affine events representable by +the concrete codes. The certificate is part of the program's output. This +result does not bound the length of a program producing it. +-/ + +@[expose] public section + +namespace Klr.AffineCode + +open FiniteMeasure + +theorem getD_ofFn {α : Type*} {n : ℕ} (f : Fin n → α) (i : Fin n) (d : α) : + (List.ofFn f).getD i.val d = f i := by + simp [List.getD_eq_getElem?_getD, i.isLt] + +/-- Encode a finite matrix, syndrome and right-inverse candidate as ordinary finite data. -/ +def encode {m r : ℕ} (A : Matrix (Fin r) (Fin m) (ZMod 2)) (y : Fin r → ZMod 2) + (R : Matrix (Fin m) (Fin r) (ZMod 2)) : Data := + ((m, r), (List.ofFn (fun i => List.ofFn (fun j => boolEquivF2.symm (A i j))), + (List.ofFn (fun i => boolEquivF2.symm (y i)), + List.ofFn (fun i => List.ofFn (fun j => boolEquivF2.symm (R i j)))))) + +@[simp] theorem width_encode {m r : ℕ} (A : Matrix (Fin r) (Fin m) (ZMod 2)) + (y : Fin r → ZMod 2) (R : Matrix (Fin m) (Fin r) (ZMod 2)) : + width (encode A y R) = m := rfl + +@[simp] theorem rank_encode {m r : ℕ} (A : Matrix (Fin r) (Fin m) (ZMod 2)) + (y : Fin r → ZMod 2) (R : Matrix (Fin m) (Fin r) (ZMod 2)) : + rank (encode A y R) = r := rfl + +@[simp] theorem matrix_encode {m r : ℕ} (A : Matrix (Fin r) (Fin m) (ZMod 2)) + (y : Fin r → ZMod 2) (R : Matrix (Fin m) (Fin r) (ZMod 2)) : + matrix (encode A y R) = A := by + ext i j + change Fin r at i + change Fin m at j + dsimp only [matrix, rows, encode, entry] + rw [getD_ofFn _ i, getD_ofFn _ j, Equiv.apply_symm_apply] + +@[simp] theorem rightMatrix_encode {m r : ℕ} (A : Matrix (Fin r) (Fin m) (ZMod 2)) + (y : Fin r → ZMod 2) (R : Matrix (Fin m) (Fin r) (ZMod 2)) : + rightMatrix (encode A y R) = R := by + ext i j + change Fin m at i + change Fin r at j + dsimp only [rightMatrix, certificate, encode, entry] + rw [getD_ofFn _ i, getD_ofFn _ j, Equiv.apply_symm_apply] + +@[simp] theorem syndromeVector_encode {m r : ℕ} + (A : Matrix (Fin r) (Fin m) (ZMod 2)) (y : Fin r → ZMod 2) + (R : Matrix (Fin m) (Fin r) (ZMod 2)) : syndromeVector (encode A y R) = y := by + funext i + change Fin r at i + dsimp only [syndromeVector, syndrome, encode] + rw [getD_ofFn _ i, Equiv.apply_symm_apply] + +theorem valid_encode_iff {m r : ℕ} (A : Matrix (Fin r) (Fin m) (ZMod 2)) + (y : Fin r → ZMod 2) (R : Matrix (Fin m) (Fin r) (ZMod 2)) : + valid (encode A y R) = true ↔ A * R = 1 := by + rw [valid_iff_right_inverse, matrix_encode, rightMatrix_encode] + rfl + +@[simp] theorem event_encode {m r : ℕ} (A : Matrix (Fin r) (Fin m) (ZMod 2)) + (y : Fin r → ZMod 2) (R : Matrix (Fin m) (Fin r) (ZMod 2)) : + event (encode A y R) = + FiniteStage.affineEvent (fun i : Fin m => i.val) A.mulVecLin y := by + simp only [event, matrix_encode, syndromeVector_encode, width_encode] + rfl + +/-- Preimages of the standard basis vectors are the columns of a right inverse. -/ +theorem exists_right_inverse {m r : ℕ} (A : Matrix (Fin r) (Fin m) (ZMod 2)) + (hA : Function.Surjective A.mulVecLin) : + ∃ R : Matrix (Fin m) (Fin r) (ZMod 2), A * R = 1 := by + classical + choose x hx using fun j : Fin r => hA (fun i => (1 : Matrix (Fin r) (Fin r) (ZMod 2)) i j) + refine ⟨fun k j => x j k, ?_⟩ + ext i j + exact congrFun (hx j) i + +/-- Every full-row-rank finite binary affine system occurs in the concrete code family. -/ +theorem exists_valid_code {m r : ℕ} (A : Matrix (Fin r) (Fin m) (ZMod 2)) + (hA : Function.Surjective A.mulVecLin) (y : Fin r → ZMod 2) : + ∃ c : Data, width c = m ∧ rank c = r ∧ valid c = true ∧ + event c = FiniteStage.affineEvent (fun i : Fin m => i.val) A.mulVecLin y := by + obtain ⟨R, hR⟩ := exists_right_inverse A hA + exact ⟨encode A y R, rfl, rfl, (valid_encode_iff A y R).mpr hR, event_encode A y R⟩ + +/-- Padding unused coordinates by zero columns represents every existing finite-support block. -/ +theorem exists_valid_code_of_affineBlock (B : AffineBlock) : + ∃ c : Data, rank c = B.rank ∧ valid c = true ∧ event c = B.event := by + classical + let m := B.support.sup id + 1 + have hbound (i : B.support) : i.val < m := + Nat.lt_succ_of_le (Finset.le_sup (f := id) i.property) + let restrict : (Fin m → ZMod 2) →ₗ[ZMod 2] (B.support → ZMod 2) := + { toFun := fun x i => x ⟨i.val, hbound i⟩ + map_add' := fun _ _ => rfl + map_smul' := fun _ _ => rfl } + have hrestrict : Function.Surjective restrict := by + intro x + refine ⟨fun j => if hj : j.val ∈ B.support then x ⟨j.val, hj⟩ else 0, ?_⟩ + funext i + change (if hi : i.val ∈ B.support then x ⟨i.val, hi⟩ else 0) = x i + simp [i.property] + let D := B.matrix.comp restrict + let A := LinearMap.toMatrix' D + have hA : Function.Surjective A.mulVecLin := by + intro y + obtain ⟨x, hx⟩ := B.fullRank y + obtain ⟨v, hv⟩ := hrestrict x + refine ⟨v, ?_⟩ + change Matrix.mulVec (LinearMap.toMatrix' D) v = y + rw [LinearMap.toMatrix'_mulVec] + change B.matrix (restrict v) = y + rw [hv, hx] + obtain ⟨c, _, hr, hv, he⟩ := exists_valid_code A hA B.syndrome + refine ⟨c, hr, hv, he.trans ?_⟩ + ext X + change Matrix.mulVec (LinearMap.toMatrix' D) + (coordinateValues (fun i : Fin m => i.val) X) = B.syndrome ↔ _ + rw [LinearMap.toMatrix'_mulVec] + rfl + +end Klr.AffineCode diff --git a/LeanPool/KLRandomness/AffineCodePrefix.lean b/LeanPool/KLRandomness/AffineCodePrefix.lean new file mode 100644 index 0000000000..688f1e711a --- /dev/null +++ b/LeanPool/KLRandomness/AffineCodePrefix.lean @@ -0,0 +1,142 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.AffineCode + +/-! +# Finite-prefix acceptance for affine-system codes + +The checker reads a prefix covering all coordinates of the encoded system. +Its accepted cylinders have union exactly the actual affine event. +-/ + +@[expose] public section + +namespace Klr.AffineCode + +open FiniteMeasure + +theorem parity_congr (p q : ℕ → Bool) (n : ℕ) + (h : ∀ k < n, p k = q k) : parity p n = parity q n := by + induction n with + | zero => rfl + | succ n ih => + rw [parity, parity, ih (fun k hk => h k (by omega)), h n (by omega)] + +/-- Left-hand side of one parity equation evaluated on an infinite input. -/ +def equationValue (c : Data) (X : Cantor) (i : ℕ) : Bool := + parity (fun k => entry (rows c) i k && X k) (width c) + +theorem value_equationValue (c : Data) (X : Cantor) (i : Fin (rank c)) : + boolEquivF2 (equationValue c X i.val) = + (matrix c).mulVecLin (coordinateValues (fun j : Fin (width c) => j.val) X) i := by + simp only [equationValue, value_parity, value_and, Matrix.mulVecLin_apply, + Matrix.mulVec, dotProduct, matrix, coordinateValues_apply] + +theorem mem_event_iff (c : Data) (X : Cantor) : + X ∈ event c ↔ ∀ i < rank c, + equationValue c X i = (syndrome c).getD i false := by + change (matrix c).mulVecLin (coordinateValues _ X) = syndromeVector c ↔ _ + constructor + · intro h i hi + apply boolEquivF2.injective + rw [value_equationValue c X ⟨i, hi⟩, h] + rfl + · intro h + funext i + rw [← value_equationValue, h i.val i.isLt] + rfl + +/-- Left-hand side on the extension of a finite prefix by zero bits. -/ +def rowValue (c : Data) (s : List Bool) (i : ℕ) : Bool := + equationValue c (fun k => s.getD k false) i + +theorem computable_rowValue : + Computable (fun p : (Data × List Bool) × ℕ => rowValue p.1.1 p.1.2 p.2) := by + have hd : Computable (fun p : ((Data × List Bool) × ℕ) × ℕ => p.1.1.1) := + Computable.fst.comp (Computable.fst.comp Computable.fst) + have hi : Computable (fun p : ((Data × List Bool) × ℕ) × ℕ => p.1.2) := + Computable.snd.comp Computable.fst + have hk : Computable (fun p : ((Data × List Bool) × ℕ) × ℕ => p.2) := Computable.snd + have hs : Computable (fun p : ((Data × List Bool) × ℕ) × ℕ => p.1.1.2) := + Computable.snd.comp (Computable.fst.comp Computable.fst) + have ha := computable_entry.comp ((computable_rows.comp hd).pair (hi.pair hk)) + have hb := (Primrec.list_getD false).to_comp.comp hs hk + have hand := Primrec.and.to_comp.comp ha hb + have hw : Computable (fun p : (Data × List Bool) × ℕ => width p.1.1) := + computable_width.comp (Computable.fst.comp Computable.fst) + have hc := (computable_parity (p := fun p : (Data × List Bool) × ℕ => fun k => + entry (rows p.1.1) p.2 k && p.1.2.getD k false) hand).comp + (Computable.id.pair hw) + exact hc.of_eq fun _ => rfl + +/-- The prefix covers the width and satisfies every encoded equation. -/ +def accepts (c : Data) (s : List Bool) : Bool := + decide (width c ≤ s.length) && EffectiveScan.boundedAll + (fun i => decide (rowValue c s i = (syndrome c).getD i false)) (rank c) + +theorem accepts_eq_true (c : Data) (s : List Bool) : + accepts c s = true ↔ width c ≤ s.length ∧ + ∀ i < rank c, rowValue c s i = (syndrome c).getD i false := by + simp only [accepts, Bool.and_eq_true, decide_eq_true_eq, + EffectiveScan.boundedAll_eq_true] + +theorem computable_accepts : Computable₂ accepts := by + have hd : Computable (fun p : (Data × List Bool) × ℕ => p.1.1) := + Computable.fst.comp Computable.fst + have hi : Computable (fun p : (Data × List Bool) × ℕ => p.2) := Computable.snd + have hy := (Primrec.list_getD false).to_comp.comp (computable_syndrome.comp hd) hi + have he := Primrec.eq.decide.to_comp.comp computable_rowValue hy + have hr : Computable (fun p : Data × List Bool => rank p.1) := + computable_rank.comp Computable.fst + have hall := (EffectiveScan.computable_boundedAll + (p := fun p : Data × List Bool => fun i => + decide (rowValue p.1 p.2 i = (syndrome p.1).getD i false)) he).comp + (Computable.id.pair hr) + have hw : Computable (fun p : Data × List Bool => width p.1) := + computable_width.comp Computable.fst + have hl : Computable (fun p : Data × List Bool => p.2.length) := + Computable.list_length.comp Computable.snd + have hwidth := Primrec.nat_le.decide.to_comp.comp hw hl + exact (Primrec.and.to_comp.comp hwidth hall).of_eq fun _ => rfl + +theorem cylinder_subset_event {c : Data} {s : List Bool} (hs : accepts c s = true) : + cylinder s ⊆ event c := by + obtain ⟨hwidth, heq⟩ := (accepts_eq_true c s).mp hs + intro X hX + apply (mem_event_iff c X).mpr + intro i hi + rw [← heq i hi] + apply parity_congr + intro k hk + rw [(mem_cylinder.mp hX) k (lt_of_lt_of_le hk hwidth)] + +theorem accepts_inputPrefix {c : Data} {X : Cantor} (hX : X ∈ event c) : + accepts c (ScanRule.inputPrefix X (width c)) = true := by + apply (accepts_eq_true _ _).mpr + refine ⟨by simp, ?_⟩ + intro i hi + rw [← (mem_event_iff c X).mp hX i hi] + apply parity_congr + intro k hk + dsimp only + rw [ScanRule.getD_inputPrefix X hk] + +theorem cylinderUnion_accepts (c : Data) : + cylinderUnion (fun s => accepts c s = true) = event c := by + ext X + constructor + · rintro ⟨s, hs, hX⟩ + exact cylinder_subset_event hs hX + · intro hX + exact ⟨ScanRule.inputPrefix X (width c), accepts_inputPrefix hX, + ScanRule.mem_cylinder_inputPrefix X (width c)⟩ + +end Klr.AffineCode diff --git a/LeanPool/KLRandomness/AffineDescription.lean b/LeanPool/KLRandomness/AffineDescription.lean new file mode 100644 index 0000000000..8f1aef260e --- /dev/null +++ b/LeanPool/KLRandomness/AffineDescription.lean @@ -0,0 +1,265 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.AffineCodePrefix +public import LeanPool.KLRandomness.AffineCodeCoverage +public import LeanPool.KLRandomness.DescriptionBudget +public import LeanPool.KLRandomness.EffectiveNormalization +public import Mathlib.Data.Nat.Bits +import Mathlib.Tactic.NormNum +import Mathlib.Tactic.Positivity + +/-! +# A concrete affine-description Martin-Löf test + +Plain binary strings are interpreted as binary natural numbers encoding a +pair of a Mathlib partial-recursive program and its natural input. A halting +program's output decodes to finite affine data. The verifier, rank threshold and finite +prefix checker are total computable functions. They give a uniformly c.e. +description family with the required measure budget. + +This construction supplies the interpreter and test, but makes no short +description claim for the particular systems chosen by the paper's stages. +-/ + +@[expose] public section + +namespace Klr.AffineDescription + +open MeasureTheory +open scoped ENNReal + +/-- Binary numeral value, with the least significant bit first. -/ +def binaryValue (p : List Bool) : ℕ := p.reverse.foldl (fun n b => Nat.bit b n) 0 + +@[simp] theorem binaryValue_nil : binaryValue [] = 0 := rfl + +@[simp] theorem binaryValue_cons (b : Bool) (p : List Bool) : + binaryValue (b :: p) = Nat.bit b (binaryValue p) := by + simp [binaryValue, List.foldl_append] + +@[simp] theorem binaryValue_bits (n : ℕ) : binaryValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp + | bit b n h ih => simp [Nat.bits_append_bit _ _ h, ih] + +theorem computable_binaryValue : Computable binaryValue := by + have hn : Computable (fun p : ℕ × Bool => p.1) := Computable.fst + have hb : Computable (fun p : ℕ × Bool => p.2) := Computable.snd + have hdouble := Primrec.nat_mul.to_comp.comp (Computable.const 2) hn + have hone := Primrec.nat_add.to_comp.comp hdouble (Computable.const 1) + have hs : Computable₂ (fun n b => Nat.bit b n) := by + apply (hb.cond hone hdouble).of_eq + intro p + cases p.2 <;> simp [Nat.bit] + exact (computable_list_foldl (fun n b => Nat.bit b n) hs 0).comp + Primrec.list_reverse.to_comp + +/-- The actual Mathlib partial-recursive code designated by the binary program. -/ +def programCode (p : List Bool) : Nat.Partrec.Code := + Denumerable.ofNat Nat.Partrec.Code (binaryValue p).unpair.1 + +/-- Numerical input supplied alongside the fixed program header. -/ +def programInput (p : List Bool) : ℕ := (binaryValue p).unpair.2 + +/-- Package a fixed partial-recursive algorithm and a numerical parameter as plain bits. -/ +def programFor (e : Nat.Partrec.Code) (n : ℕ) : List Bool := + (Nat.pair (Encodable.encode e) n).bits + +@[simp] theorem programCode_programFor (e : Nat.Partrec.Code) (n : ℕ) : + programCode (programFor e n) = e := by + simp [programCode, programFor, Denumerable.ofNat_encode] + +@[simp] theorem programInput_programFor (e : Nat.Partrec.Code) (n : ℕ) : + programInput (programFor e n) = n := by + simp [programInput, programFor] + +theorem computable_programCode : Computable programCode := + (Computable.ofNat Nat.Partrec.Code).comp + (Computable.fst.comp (Primrec.unpair.to_comp.comp computable_binaryValue)) + +theorem computable_programInput : Computable programInput := + Computable.snd.comp (Primrec.unpair.to_comp.comp computable_binaryValue) + +/-- Interpret a natural output as affine data; unused encodings decode to zero data. -/ +def decodeOutput (n : ℕ) : AffineCode.Data := + (Encodable.decode (α := AffineCode.Data) n).getD default + +theorem computable_decodeOutput : Computable decodeOutput := + Primrec.option_getD_default.to_comp.comp Computable.decode + +@[simp] theorem decodeOutput_encode (c : AffineCode.Data) : + decodeOutput (Encodable.encode c) = c := by + simp [decodeOutput] + +/-- Run the designated partial-recursive code on its designated input and decode the output. -/ +def run (p : List Bool) : Part AffineCode.Data := + ((programCode p).eval (programInput p)).map decodeOutput + +@[simp] theorem run_programFor (e : Nat.Partrec.Code) (n : ℕ) : + run (programFor e n) = (e.eval n).map decodeOutput := by + simp [run] + +theorem partrec_run : Partrec run := by + have he := Nat.Partrec.Code.eval_part.comp computable_programCode computable_programInput + have hd : Computable₂ (fun (_ : List Bool) (n : ℕ) => decodeOutput n) := + computable_decodeOutput.comp Computable.snd + exact he.map hd + +/-- Every finite affine code is the output of some plain binary program. +No length bound is asserted here. -/ +theorem exists_program (c : AffineCode.Data) : ∃ p : List Bool, c ∈ run p := by + refine ⟨programFor Nat.Partrec.Code.id (Encodable.encode c), ?_⟩ + simp + +/-- Every finite-support affine block has a successfully evaluated exact description. +The later stage construction must additionally prove a sufficiently small program length. -/ +theorem exists_program_of_affineBlock (B : AffineBlock) : + ∃ (p : List Bool) (c : AffineCode.Data), c ∈ run p ∧ + AffineCode.valid c = true ∧ AffineCode.rank c = B.rank ∧ + AffineCode.event c = B.event := by + obtain ⟨c, hr, hv, he⟩ := AffineCode.exists_valid_code_of_affineBlock B + obtain ⟨p, hp⟩ := exists_program c + exact ⟨p, c, hp, hv, hr, he⟩ + +/-- The wholly finite filter following a successful program evaluation. -/ +def check (a : ℕ × List Bool × List Bool) (c : AffineCode.Data) : Bool := + AffineCode.valid c && (decide (2 * a.2.1.length + a.1 + 1 ≤ AffineCode.rank c) && + AffineCode.accepts c a.2.2) + +theorem check_eq_true (a : ℕ × List Bool × List Bool) (c : AffineCode.Data) : + check a c = true ↔ AffineCode.valid c = true ∧ + 2 * a.2.1.length + a.1 + 1 ≤ AffineCode.rank c ∧ + AffineCode.accepts c a.2.2 = true := by + simp [check] + +theorem computable_check : Computable₂ check := by + have hd : Computable (fun p : (ℕ × List Bool × List Bool) × AffineCode.Data => p.2) := + Computable.snd + have hn : Computable (fun p : (ℕ × List Bool × List Bool) × AffineCode.Data => p.1.1) := + Computable.fst.comp Computable.fst + have hp : Computable (fun p : (ℕ × List Bool × List Bool) × AffineCode.Data => p.1.2.1) := + Computable.fst.comp (Computable.snd.comp Computable.fst) + have hs : Computable (fun p : (ℕ × List Bool × List Bool) × AffineCode.Data => p.1.2.2) := + Computable.snd.comp (Computable.snd.comp Computable.fst) + have hlen := Computable.list_length.comp hp + have htwice := Primrec.nat_mul.to_comp.comp (Computable.const 2) hlen + have hbudget := Primrec.nat_add.to_comp.comp + (Primrec.nat_add.to_comp.comp htwice hn) (Computable.const 1) + have hrank := Primrec.nat_le.decide.to_comp.comp hbudget (AffineCode.computable_rank.comp hd) + have ha := AffineCode.computable_accepts.comp hd hs + have hc := Primrec.and.to_comp.comp (AffineCode.computable_valid.comp hd) + (Primrec.and.to_comp.comp hrank ha) + exact hc.of_eq fun _ => rfl + +/-- The affine-description cylinder enumeration. -/ +def W (a : ℕ × List Bool × List Bool) : Prop := + ∃ c : AffineCode.Data, c ∈ run a.2.1 ∧ AffineCode.valid c = true ∧ + 2 * a.2.1.length + a.1 + 1 ≤ AffineCode.rank c ∧ + AffineCode.accepts c a.2.2 = true + +/-- Uniform enumerability follows from actual partial evaluation and the total finite filter. -/ +theorem rePred_W : REPred W := by + let accept (a : ℕ × List Bool × List Bool) : Part Unit := + (run a.2.1).bind fun c => if check a c then Part.some () else Part.none + have hp : Computable (fun a : ℕ × List Bool × List Bool => a.2.1) := + Computable.fst.comp Computable.snd + have hfilter : Partrec (fun p : (ℕ × List Bool × List Bool) × AffineCode.Data => + if check p.1 p.2 then Part.some () else Part.none) := by + have ht : Partrec (fun _ : (ℕ × List Bool × List Bool) × AffineCode.Data => + Part.some ()) := (Computable.const ()).partrec + have hf : Partrec (fun _ : (ℕ × List Bool × List Bool) × AffineCode.Data => + (Part.none : Part Unit)) := Partrec.none + have hc := Partrec.cond (c := fun p : (ℕ × List Bool × List Bool) × AffineCode.Data => + check p.1 p.2) computable_check ht hf + exact hc.of_eq fun p => by cases check p.1 p.2 <;> rfl + have he : Partrec accept := (partrec_run.comp hp).bind + (g := fun a c => if check a c then Part.some () else Part.none) hfilter.to₂ + apply he.dom_re.of_eq + intro a + simp only [accept, Part.dom_iff_mem, Part.mem_bind_iff] + constructor + · rintro ⟨u, c, hc, hu⟩ + have hcheck : check a c = true := by + cases hh : check a c <;> simp [hh] at hu ⊢ + exact ⟨c, hc, (check_eq_true a c).mp hcheck⟩ + · rintro ⟨c, hc, hv, hr, hs⟩ + refine ⟨(), c, hc, ?_⟩ + simp [(check_eq_true a c).mpr ⟨hv, hr, hs⟩] + +/-- A successful verified program enumerates exactly its affine event at every eligible level. -/ +theorem cylinderUnion_W_eq {n : ℕ} {p : List Bool} {c : AffineCode.Data} + (hc : c ∈ run p) (hv : AffineCode.valid c = true) + (hr : 2 * p.length + n + 1 ≤ AffineCode.rank c) : + cylinderUnion (fun s => W (n, p, s)) = AffineCode.event c := by + rw [← AffineCode.cylinderUnion_accepts c] + congr 1 + funext s + apply propext + constructor + · rintro ⟨d, hd, _, _, hs⟩ + have hdc : d = c := Part.mem_unique hd hc + simpa only [hdc] using hs + · intro hs + exact ⟨c, hc, hv, hr, hs⟩ + +/-- Every program receives its declared plain-description measure budget. -/ +theorem per_program_bound (n : ℕ) (p : List Bool) : + fairCoin (cylinderUnion (fun s => W (n, p, s))) ≤ + (1 / 2 : ℝ≥0∞) ^ (2 * p.length + n + 1) := by + classical + by_cases h : ∃ c : AffineCode.Data, c ∈ run p ∧ AffineCode.valid c = true ∧ + 2 * p.length + n + 1 ≤ AffineCode.rank c + · obtain ⟨c, hc, hv, hr⟩ := h + rw [cylinderUnion_W_eq hc hv hr, AffineCode.fairCoin_event c hv] + exact pow_le_pow_of_le_one (by positivity) (by norm_num) hr + · have hempty : cylinderUnion (fun s => W (n, p, s)) = ∅ := by + apply Set.eq_empty_iff_forall_notMem.mpr + rintro X ⟨s, ⟨c, hc, hv, hr, _⟩, _⟩ + exact h ⟨c, hc, hv, hr⟩ + rw [hempty, measure_empty] + positivity + +theorem uniformlyEffectivelyOpen : IsUniformlyEffectivelyOpen (descriptionLevel W) := + descriptionLevel_uniform rePred_W + +theorem measure_level_le (n : ℕ) : + fairCoin (descriptionLevel W n) ≤ (1 / 2 : ℝ≥0∞) ^ n := + descriptionLevel_measure_le W n (per_program_bound n) + +/-- The concrete family is a genuine Martin-Löf test with no decoder or rank-check hypothesis. -/ +theorem exists_martinLofTest : + ∃ T : MartinLofTest, ∀ n, T.level n = descriptionLevel W n := + exists_martinLofTest_of_description_family rePred_W per_program_bound + +/-- Fix one actual partial-recursive test code representing the description family. -/ +noncomputable def test : MartinLofTest := Classical.choose exists_martinLofTest + +theorem test_level (n : ℕ) : test.level n = descriptionLevel W n := + Classical.choose_spec exists_martinLofTest n + +theorem event_subset_level {n : ℕ} {p : List Bool} {c : AffineCode.Data} + (hc : c ∈ run p) (hv : AffineCode.valid c = true) + (hr : 2 * p.length + n + 1 ≤ AffineCode.rank c) : + AffineCode.event c ⊆ descriptionLevel W n := by + rw [← cylinderUnion_W_eq hc hv hr] + exact Set.subset_iUnion (fun p : List Bool => cylinderUnion (fun s => W (n, p, s))) p + +/-- The remaining application obligation is to produce sufficiently short stage programs. -/ +theorem not_martinLofRandom_of_programs {X : Cantor} + (hX : ∀ n, ∃ (p : List Bool) (c : AffineCode.Data), c ∈ run p ∧ + AffineCode.valid c = true ∧ 2 * p.length + n + 1 ≤ AffineCode.rank c ∧ + X ∈ AffineCode.event c) : ¬MartinLofRandom X := by + apply not_martinLofRandom_of_descriptions rePred_W per_program_bound + intro n + obtain ⟨p, c, hc, hv, hr, hmem⟩ := hX n + exact ⟨p, by rwa [cylinderUnion_W_eq hc hv hr]⟩ + +end Klr.AffineDescription diff --git a/LeanPool/KLRandomness/AffineDescriptionSeparation.lean b/LeanPool/KLRandomness/AffineDescriptionSeparation.lean new file mode 100644 index 0000000000..10e158b753 --- /dev/null +++ b/LeanPool/KLRandomness/AffineDescriptionSeparation.lean @@ -0,0 +1,61 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.AffineDescription +public import LeanPool.KLRandomness.StageEstimates + +/-! +# Separation reduction with the concrete affine interpreter + +The remaining hypotheses concern the actual blocks, their stage estimates, +and sufficiently short binary programs describing events that cover their +solutions. Uniform enumerability and the Martin-Löf measure bounds are +discharged by the implemented interpreter and verifier. + +These are conditional separation theorems. The separate `StageConstruction` +development supplies their actual stage sequence and short-program bounds; +`Separation` obtains the resulting unconditional existence theorem. +-/ + +@[expose] public section + +namespace Klr + +/-- Actual stage estimates and short, successfully evaluated affine programs imply separation. +The program may describe any verified affine event containing the selected block event. -/ +theorem exists_separating_of_stage_estimates_and_affine_programs (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) (V : ℕ → ℕ) + (hstage : ∀ s : BettingStrategy, ∃ (H : Set Cantor) (J : ℕ), + StageEstimates B s.normalize.scan s.normalize.capital.wager V H J) + (hprogram : ∀ n : ℕ, ∃ (j : ℕ) (p : List Bool) (c : AffineCode.Data), + c ∈ AffineDescription.run p ∧ AffineCode.valid c = true ∧ + 2 * p.length + n + 1 ≤ AffineCode.rank c ∧ (B j).event ⊆ AffineCode.event c) : + ∃ X : Cantor, KolmogorovLovelandRandom X ∧ ¬MartinLofRandom X := by + apply exists_separating_of_stage_estimates_and_descriptions B hdis V hstage + AffineDescription.rePred_W AffineDescription.per_program_bound + intro n + obtain ⟨j, p, c, hc, hv, hr, hcover⟩ := hprogram n + exact ⟨j, p, by rwa [AffineDescription.cylinderUnion_W_eq hc hv hr]⟩ + +/-- Describing the selected block's exact event is a sufficient special case of the cover. -/ +theorem exists_separating_of_stage_estimates_and_exact_affine_programs (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) (V : ℕ → ℕ) + (hstage : ∀ s : BettingStrategy, ∃ (H : Set Cantor) (J : ℕ), + StageEstimates B s.normalize.scan s.normalize.capital.wager V H J) + (hprogram : ∀ n : ℕ, ∃ (j : ℕ) (p : List Bool) (c : AffineCode.Data), + c ∈ AffineDescription.run p ∧ AffineCode.valid c = true ∧ + 2 * p.length + n + 1 ≤ AffineCode.rank c ∧ AffineCode.event c = (B j).event) : + ∃ X : Cantor, KolmogorovLovelandRandom X ∧ ¬MartinLofRandom X := by + apply exists_separating_of_stage_estimates_and_affine_programs B hdis V hstage + intro n + obtain ⟨j, p, c, hc, hv, hr, he⟩ := hprogram n + exact ⟨j, p, c, hc, hv, hr, he.symm.subset⟩ + +end Klr diff --git a/LeanPool/KLRandomness/AffineFamily.lean b/LeanPool/KLRandomness/AffineFamily.lean new file mode 100644 index 0000000000..b775d152a4 --- /dev/null +++ b/LeanPool/KLRandomness/AffineFamily.lean @@ -0,0 +1,109 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.AffineBlock +import Mathlib.Tactic.NormNum + +/-! +# Positive finite-stage laws for disjoint affine blocks + +Pairwise disjoint full-row-rank blocks have the product of their syndrome +probabilities. Hence conditioning on any finite family is well defined as a +probability measure, without a separate nonnull-background assumption. +-/ + +@[expose] public section + +namespace Klr.AffineBlock + +open MeasureTheory ProbabilityTheory +open FiniteStage +open scoped ENNReal + +theorem fairCoin_finset_familyEvent {κ : Type*} (B : κ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) (J : Finset κ) : + fairCoin {X | ∀ k ∈ J, X ∈ (B k).event} = + ∏ k ∈ J, (1 / 2 : ℝ≥0∞) ^ (B k).rank := by + classical + induction J using Finset.induction_on with + | empty => simp + | @insert k J hk ih => + let A : Set Cantor := {X | ∀ i ∈ J, X ∈ (B i).event} + let H := J.biUnion (fun i => (B i).support) + have hA : DependsOn (fun X : Cantor => X ∈ A) (H : Set ℕ) := by + intro X Y hxy + have he (i : κ) (hi : i ∈ J) : (X ∈ (B i).event) = (Y ∈ (B i).event) := by + apply (B i).dependsOn_event + intro n hn + exact hxy n (Finset.mem_biUnion.mpr ⟨i, hi, hn⟩) + apply propext + constructor + · intro hX i hi + exact (iff_of_eq (he i hi)).mp (hX i hi) + · intro hY i hi + exact (iff_of_eq (he i hi)).mpr (hY i hi) + have hd : Disjoint (B k).support H := by + rw [Finset.disjoint_left] + intro n hn hm + obtain ⟨i, hi, hni⟩ := Finset.mem_biUnion.mp hm + have hki : k ≠ i := by rintro rfl; exact hk hi + exact Finset.disjoint_left.mp (hdis hki) hn hni + have he : {X | ∀ i ∈ insert k J, X ∈ (B i).event} = (B k).event ∩ A := by + ext X + simp [A] + rw [he, fairCoin_inter_of_disjoint_support (B k).event A (B k).support H + (B k).dependsOn_event hA hd, (B k).fairCoin_event, Finset.prod_insert hk] + exact congrArg ((1 / 2 : ℝ≥0∞) ^ (B k).rank * ·) ih + +/-- Exact measure of a finite family of pairwise disjoint block constraints. -/ +theorem fairCoin_familyEvent {κ : Type*} [Fintype κ] (B : κ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) : + fairCoin (familyEvent B) = ∏ k, (1 / 2 : ℝ≥0∞) ^ (B k).rank := by + simpa [familyEvent] using fairCoin_finset_familyEvent B hdis Finset.univ + +/-- Finite, disjoint, full-rank constraints always have a nonnull conjunction. -/ +theorem fairCoin_familyEvent_ne_zero {κ : Type*} [Finite κ] (B : κ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) : + fairCoin (familyEvent B) ≠ 0 := by + let _ := Fintype.ofFinite κ + rw [fairCoin_familyEvent B hdis] + exact Finset.prod_ne_zero_iff.mpr (fun k _ => pow_ne_zero _ (by norm_num)) + +theorem finiteStageLaw_isProbabilityMeasure_of_disjoint {κ : Type*} [Finite κ] + (B : κ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) : + IsProbabilityMeasure (finiteStageLaw B) := + finiteStageLaw_isProbabilityMeasure B (fairCoin_familyEvent_ne_zero B hdis) + +/-- The new syndrome has its uniform probability under every valid previous finite stage. -/ +theorem finiteStageLaw_event_of_disjoint {κ : Type*} [Finite κ] (old : κ → AffineBlock) + (B : AffineBlock) + (hold : Pairwise (fun i j => Disjoint (old i).support (old j).support)) + (hnew : ∀ k, Disjoint (old k).support B.support) : + (finiteStageLaw old) B.event = (1 / 2 : ℝ≥0∞) ^ B.rank := + finiteStageLaw_event old B hnew (fairCoin_familyEvent_ne_zero old hold) + +/-- Adding a disjoint block does not change a transcript probability while that block's +unread columns still have full row rank. Both sides are actual conditioned measures. -/ +theorem nextStageLaw_transcript {κ : Type*} [Finite κ] (old : κ → AffineBlock) + (B : AffineBlock) + (hold : Pairwise (fun i j => Disjoint (old i).support (old j).support)) + (hnew : ∀ k, Disjoint (old k).support B.support) + (π : ScanRule) (v : List Bool) (hfull : B.UnreadFullRank π v) : + (cond fairCoin (familyEvent old ∩ B.event)) {X | π.transcript X v.length = v} = + (finiteStageLaw old) {X | π.transcript X v.length = v} := by + rw [← cond_cond_eq_cond_inter (measurableSet_familyEvent old) B.measurableSet_event fairCoin] + change (cond (finiteStageLaw old) B.event) {X | π.transcript X v.length = v} = _ + rw [cond_apply B.measurableSet_event, Set.inter_comm, + finiteStage_identity old B hnew π v hfull, + finiteStageLaw_event_of_disjoint old B hold hnew, ← mul_assoc, + ENNReal.inv_mul_cancel (pow_ne_zero _ (by norm_num)) (by finiteness), one_mul] + +end Klr.AffineBlock diff --git a/LeanPool/KLRandomness/AffineObservation.lean b/LeanPool/KLRandomness/AffineObservation.lean new file mode 100644 index 0000000000..1647bac2f0 --- /dev/null +++ b/LeanPool/KLRandomness/AffineObservation.lean @@ -0,0 +1,253 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.Affine +import Mathlib.Tactic.Abel +import Mathlib.Tactic.Positivity + +/-! +# Counting affine constraints after a fixed observation + +The observed coordinates form an arbitrary decidable subset of a finite index +set. Extending the unread coordinates by zero defines the remaining-column +linear map. If this map is surjective, every residual syndrome has the same +number of completions. An arbitrary condition on the observed coordinates +can be retained throughout, so earlier disjoint constraints and transcript +conditions can be included in the counting identity. +-/ + +@[expose] public section + +namespace Klr.AffineObservation + +variable {ι : Type*} + +/-- The values on the observed coordinates. -/ +def observedPart (O : Set ι) (x : ι → ZMod 2) : O → ZMod 2 := fun i => x i.val + +/-- The values on the unread coordinates. -/ +def unreadPart (O : Set ι) (x : ι → ZMod 2) : {i // i ∉ O} → ZMod 2 := + fun i => x i.val + +/-- Extend an assignment on observed coordinates by zero elsewhere. -/ +def extendObserved (O : Set ι) [DecidablePred (· ∈ O)] : + (O → ZMod 2) →ₗ[ZMod 2] (ι → ZMod 2) where + toFun o i := if h : i ∈ O then o ⟨i, h⟩ else 0 + map_add' a b := by ext i; by_cases h : i ∈ O <;> simp [h] + map_smul' a b := by ext i; by_cases h : i ∈ O <;> simp [h] + +/-- Extend an assignment on unread coordinates by zero on the observed coordinates. -/ +def extendUnread (O : Set ι) [DecidablePred (· ∈ O)] : + ({i // i ∉ O} → ZMod 2) →ₗ[ZMod 2] (ι → ZMod 2) where + toFun u i := if h : i ∈ O then 0 else u ⟨i, h⟩ + map_add' a b := by ext i; by_cases h : i ∈ O <;> simp [h] + map_smul' a b := by ext i; by_cases h : i ∈ O <;> simp [h] + +/-- Combine observed and unread assignments. -/ +def merge (O : Set ι) [DecidablePred (· ∈ O)] (o : O → ZMod 2) + (u : {i // i ∉ O} → ZMod 2) : ι → ZMod 2 := + extendObserved O o + extendUnread O u + +@[simp] theorem observedPart_merge (O : Set ι) [DecidablePred (· ∈ O)] + (o : O → ZMod 2) (u : {i // i ∉ O} → ZMod 2) : + observedPart O (merge O o u) = o := by + funext i + simp [observedPart, merge, extendObserved, extendUnread, i.property] + +@[simp] theorem unreadPart_merge (O : Set ι) [DecidablePred (· ∈ O)] + (o : O → ZMod 2) (u : {i // i ∉ O} → ZMod 2) : + unreadPart O (merge O o u) = u := by + funext i + simp [unreadPart, merge, extendObserved, extendUnread, i.property] + +@[simp] theorem merge_parts (O : Set ι) [DecidablePred (· ∈ O)] (x : ι → ZMod 2) : + merge O (observedPart O x) (unreadPart O x) = x := by + funext i + by_cases h : i ∈ O <;> + simp [merge, observedPart, unreadPart, extendObserved, extendUnread, h] + +/-- Splitting all coordinates into the observed and unread parts is a bijection. -/ +def splitEquiv (O : Set ι) [DecidablePred (· ∈ O)] : + (ι → ZMod 2) ≃ (O → ZMod 2) × ({i // i ∉ O} → ZMod 2) where + toFun x := (observedPart O x, unreadPart O x) + invFun p := merge O p.1 p.2 + left_inv := merge_parts O + right_inv p := by simp + +/-- The remaining-column map after the coordinates in `O` have been observed. -/ +def unreadMap {r : ℕ} (D : (ι → ZMod 2) →ₗ[ZMod 2] (Fin r → ZMod 2)) + (O : Set ι) [DecidablePred (· ∈ O)] : + ({i // i ∉ O} → ZMod 2) →ₗ[ZMod 2] (Fin r → ZMod 2) := + D.comp (extendUnread O) + +/-- A background condition that depends only on the observed coordinates. -/ +def background (O : Set ι) (P : (O → ZMod 2) → Prop) : Set (ι → ZMod 2) := + {x | P (observedPart O x)} + +/-- The background condition together with a specified affine syndrome. -/ +def joint {r : ℕ} (D : (ι → ZMod 2) →ₗ[ZMod 2] (Fin r → ZMod 2)) + (O : Set ι) (P : (O → ZMod 2) → Prop) (y : Fin r → ZMod 2) : Set (ι → ZMod 2) := + {x | P (observedPart O x) ∧ D x = y} + +/-- With the observed part fixed, the only equation left is the residual syndrome equation. -/ +def jointEquivSigma {r : ℕ} (D : (ι → ZMod 2) →ₗ[ZMod 2] (Fin r → ZMod 2)) + (O : Set ι) [DecidablePred (· ∈ O)] (P : (O → ZMod 2) → Prop) + (y : Fin r → ZMod 2) : + joint D O P y ≃ Σ o : {o : O → ZMod 2 // P o}, + Affine.Fiber (unreadMap D O) (y - D (extendObserved O o.val)) where + toFun x := ⟨⟨observedPart O x.val, x.property.1⟩, ⟨unreadPart O x.val, by + change D (extendUnread O (unreadPart O x.val)) = + y - D (extendObserved O (observedPart O x.val)) + apply eq_sub_iff_add_eq.mpr + rw [← map_add, add_comm] + change D (merge O (observedPart O x.val) (unreadPart O x.val)) = y + rw [merge_parts] + exact x.property.2⟩⟩ + invFun p := ⟨merge O p.1.val p.2.val, by + constructor + · simpa using p.1.property + · dsimp [merge] + rw [map_add] + change D (extendObserved O p.1.val) + unreadMap D O p.2.val = y + rw [p.2.property] + abel⟩ + left_inv x := by + apply Subtype.ext + exact merge_parts O x.val + right_inv p := by + rcases p with ⟨⟨o, ho⟩, ⟨u, hu⟩⟩ + apply Sigma.ext (Subtype.ext (observedPart_merge O o u)) + apply (Subtype.heq_iff_coe_eq (fun v => by simp only [observedPart_merge])).mpr + exact unreadPart_merge O o u + +/-- Background assignments are freely parametrized by their unread coordinates. -/ +def backgroundEquivProd (O : Set ι) [DecidablePred (· ∈ O)] + (P : (O → ZMod 2) → Prop) : + background O P ≃ {o : O → ZMod 2 // P o} × ({i // i ∉ O} → ZMod 2) where + toFun x := (⟨observedPart O x.val, x.property⟩, unreadPart O x.val) + invFun p := ⟨merge O p.1.val p.2, by simpa [background] using p.1.property⟩ + left_inv x := by apply Subtype.ext; exact merge_parts O x.val + right_inv p := by rcases p with ⟨⟨o, ho⟩, u⟩; simp + +/-- An assignment vanishing on the observed coordinates is entirely its unread extension. -/ +theorem extendUnread_unreadPart_of_observed_zero (O : Set ι) + [DecidablePred (· ∈ O)] (x : ι → ZMod 2) (hx : observedPart O x = 0) : + extendUnread O (unreadPart O x) = x := by + have h := merge_parts O x + dsimp [merge] at h + rw [hx, map_zero, zero_add] at h + exact h + +/-- To prove surjectivity of the remaining-column map, it suffices to lift every syndrome +through assignments supported on unread coordinates. This allows a smaller block to be +embedded in a larger finite ambient coordinate set. -/ +theorem unreadMap_surjective_of_supported_lift {α : Type*} {r : ℕ} + (D : (ι → ZMod 2) →ₗ[ZMod 2] (Fin r → ZMod 2)) + (O : Set ι) [DecidablePred (· ∈ O)] (L : α → (ι → ZMod 2)) + (hzero : ∀ a, observedPart O (L a) = 0) + (hsurj : Function.Surjective (fun a => D (L a))) : + Function.Surjective (unreadMap D O) := by + intro y + obtain ⟨a, ha⟩ := hsurj y + refine ⟨unreadPart O (L a), ?_⟩ + change D (extendUnread O (unreadPart O (L a))) = y + rw [extendUnread_unreadPart_of_observed_zero O (L a) (hzero a)] + exact ha + +/-- A surjective remaining-column map has at most as many rows as unread coordinates. -/ +theorem unread_rank_le [Fintype ι] {r : ℕ} + (D : (ι → ZMod 2) →ₗ[ZMod 2] (Fin r → ZMod 2)) + (O : Set ι) [DecidablePred (· ∈ O)] + (hD : Function.Surjective (unreadMap D O)) : + r ≤ Fintype.card {i // i ∉ O} := by + simpa using LinearMap.finrank_le_finrank_of_surjective hD + +/-- Each admissible observed assignment contributes the same number of completions. -/ +theorem card_joint [Fintype ι] {r : ℕ} + (D : (ι → ZMod 2) →ₗ[ZMod 2] (Fin r → ZMod 2)) + (O : Set ι) [DecidablePred (· ∈ O)] (P : (O → ZMod 2) → Prop) + (y : Fin r → ZMod 2) (hD : Function.Surjective (unreadMap D O)) : + Nat.card (joint D O P y) = Nat.card {o : O → ZMod 2 // P o} * + 2 ^ (Fintype.card {i // i ∉ O} - r) := by + classical + let : ∀ o : {o : O → ZMod 2 // P o}, + Finite (Affine.Fiber (unreadMap D O) (y - D (extendObserved O o.val))) := + fun _ => by unfold Affine.Fiber; infer_instance + rw [Nat.card_congr (jointEquivSigma D O P y), Nat.card_sigma] + have hcard (o : {o : O → ZMod 2 // P o}) : + Nat.card (Affine.Fiber (unreadMap D O) (y - D (extendObserved O o.val))) = + 2 ^ (Fintype.card {i // i ∉ O} - r) := by + simpa using Affine.card_fiber_of_surjective (unreadMap D O) hD + (y - D (extendObserved O o.val)) + simp_rw [hcard] + simp [Nat.card_eq_fintype_card] + +/-- The unread coordinates remain unrestricted by a condition on observed values alone. -/ +theorem card_background [Fintype ι] (O : Set ι) [DecidablePred (· ∈ O)] + (P : (O → ZMod 2) → Prop) : + Nat.card (background O P) = Nat.card {o : O → ZMod 2 // P o} * + 2 ^ Fintype.card {i // i ∉ O} := by + rw [Nat.card_congr (backgroundEquivProd O P), Nat.card_prod] + simp [Nat.card_fun, Nat.card_eq_fintype_card] + +/-- Imposing any one syndrome keeps exactly a `2⁻ʳ` fraction of every observed-coordinate +background event. The identity remains valid when the background has no assignments. -/ +theorem card_joint_mul_pow_eq_card_background [Finite ι] {r : ℕ} + (D : (ι → ZMod 2) →ₗ[ZMod 2] (Fin r → ZMod 2)) + (O : Set ι) [DecidablePred (· ∈ O)] (P : (O → ZMod 2) → Prop) + (y : Fin r → ZMod 2) (hD : Function.Surjective (unreadMap D O)) : + Nat.card (joint D O P y) * 2 ^ r = Nat.card (background O P) := by + classical + let _ := Fintype.ofFinite ι + rw [card_joint D O P y hD, card_background O P, mul_assoc, ← pow_add, + Nat.sub_add_cancel (unread_rank_le D O hD)] + +/-- The assignments extending a specified observation and realizing a syndrome. -/ +def observedFiber {r : ℕ} (D : (ι → ZMod 2) →ₗ[ZMod 2] (Fin r → ZMod 2)) + (O : Set ι) (o : O → ZMod 2) (y : Fin r → ZMod 2) : Set (ι → ZMod 2) := + joint D O (fun a => a = o) y + +/-- A fixed observation leaves exactly `2^(number of unread coordinates - r)` completions. -/ +theorem card_observedFiber [Fintype ι] {r : ℕ} + (D : (ι → ZMod 2) →ₗ[ZMod 2] (Fin r → ZMod 2)) + (O : Set ι) [DecidablePred (· ∈ O)] (o : O → ZMod 2) (y : Fin r → ZMod 2) + (hD : Function.Surjective (unreadMap D O)) : + Nat.card (observedFiber D O o y) = 2 ^ (Fintype.card {i // i ∉ O} - r) := by + rw [observedFiber, card_joint D O (fun a => a = o) y hD] + have hcard : Nat.card {a : O → ZMod 2 // a = o} = 1 := Nat.card_unique + rw [hcard, one_mul] + +/-- A fixed observation has one freely chosen bit per unread coordinate. -/ +theorem card_fixedObservation [Fintype ι] (O : Set ι) [DecidablePred (· ∈ O)] + (o : O → ZMod 2) : + Nat.card (background O (fun a => a = o)) = 2 ^ Fintype.card {i // i ∉ O} := by + rw [card_background O (fun a => a = o)] + have hcard : Nat.card {a : O → ZMod 2 // a = o} = 1 := Nat.card_unique + rw [hcard, one_mul] + +/-- Within the extensions of any fixed observation, each syndrome has the same fraction `2⁻ʳ`. -/ +theorem observedFiber_fraction [Finite ι] {r : ℕ} + (D : (ι → ZMod 2) →ₗ[ZMod 2] (Fin r → ZMod 2)) + (O : Set ι) [DecidablePred (· ∈ O)] (o : O → ZMod 2) (y : Fin r → ZMod 2) + (hD : Function.Surjective (unreadMap D O)) : + (Nat.card (observedFiber D O o y) : ℚ) / + Nat.card (background O (fun a => a = o)) = (1 / 2 : ℚ) ^ r := by + classical + let _ := Fintype.ofFinite ι + rw [card_observedFiber D O o y hD, card_fixedObservation O o] + push_cast + have hp : (2 : ℚ) ^ Fintype.card {i // i ∉ O} = + 2 ^ (Fintype.card {i // i ∉ O} - r) * 2 ^ r := by + rw [← pow_add, Nat.sub_add_cancel (unread_rank_le D O hD)] + rw [hp, div_mul_eq_div_div, div_self (by positivity : + (2 : ℚ) ^ (Fintype.card {i // i ∉ O} - r) ≠ 0)] + simp + +end Klr.AffineObservation diff --git a/LeanPool/KLRandomness/AffineProgramLength.lean b/LeanPool/KLRandomness/AffineProgramLength.lean new file mode 100644 index 0000000000..2537223e41 --- /dev/null +++ b/LeanPool/KLRandomness/AffineProgramLength.lean @@ -0,0 +1,157 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.AffineDescription +public import Mathlib.Data.Nat.Size +public import Mathlib.Order.Filter.AtTopBot.Basic +import Mathlib.Tactic.GCongr +import Mathlib.Tactic.Linarith +import Mathlib.Tactic.NormNum + +/-! +# Length of fixed-program descriptions with numerical input + +The concrete compiler packages a fixed partial-recursive program and its +numerical input using `Nat.pair`, then writes that number in binary. Pairing +costs at most twice the larger binary size. Consequently polynomially bounded +input and advice fit the affine-description test's rank budget for every +sufficiently large rank. + +This is an encoding theorem. A stage-specific reconstruction algorithm and +the correctness of its output remain separate obligations. +-/ + +@[expose] public section + +namespace Klr.AffineProgramLength + +open Filter AffineDescription + +/-- The natural-number pairing function uses at most twice the larger binary size. -/ +theorem size_pair_le (a b : ℕ) : + Nat.size (Nat.pair a b) ≤ 2 * max (Nat.size a) (Nat.size b) := by + apply Nat.size_le.mpr + have ha : a < 2 ^ max (Nat.size a) (Nat.size b) := + (Nat.lt_size_self a).trans_le + (Nat.pow_le_pow_right (by decide) (le_max_left _ _)) + have hb : b < 2 ^ max (Nat.size a) (Nat.size b) := + (Nat.lt_size_self b).trans_le + (Nat.pow_le_pow_right (by decide) (le_max_right _ _)) + have hab : max a b + 1 ≤ 2 ^ max (Nat.size a) (Nat.size b) := by omega + calc + Nat.pair a b < (max a b + 1) ^ 2 := Nat.pair_lt_max_add_one_sq a b + _ ≤ (2 ^ max (Nat.size a) (Nat.size b)) ^ 2 := by gcongr + _ = 2 ^ (2 * max (Nat.size a) (Nat.size b)) := by + rw [← pow_mul, Nat.mul_comm] + +/-- The compiler's exact bit length. -/ +theorem programFor_length (e : Nat.Partrec.Code) (n : ℕ) : + (programFor e n).length = Nat.size (Nat.pair (Encodable.encode e) n) := + Nat.size_eq_bits_len _ + +/-- A direct binary-length bound for a fixed algorithm and arbitrary numerical input. -/ +theorem programFor_length_le_max (e : Nat.Partrec.Code) (n : ℕ) : + (programFor e n).length ≤ + 2 * max (Nat.size (Encodable.encode e)) (Nat.size n) := by + rw [programFor_length] + exact size_pair_le _ _ + +/-- An additive version separates the fixed program header from the input size. -/ +theorem programFor_length_le (e : Nat.Partrec.Code) (n : ℕ) : + (programFor e n).length ≤ + 2 * (Nat.size (Encodable.encode e) + Nat.size n) := by + apply (programFor_length_le_max e n).trans + omega + +/-- A polynomial input has logarithmic binary size, including the constant polynomial. -/ +theorem size_pow_le (r k : ℕ) : Nat.size (r ^ k) ≤ k * Nat.size r + 1 := by + calc + Nat.size (r ^ k) ≤ Nat.size ((2 ^ Nat.size r) ^ k) := by + apply Nat.size_le_size + gcongr + exact (Nat.lt_size_self r).le + _ = k * Nat.size r + 1 := by + rw [← pow_mul, Nat.size_pow, Nat.mul_comm] + +/-- An elementary exponential comparison used to avoid analytic logarithm estimates. -/ +theorem sq_le_two_pow {n : ℕ} (hn : 4 ≤ n) : n ^ 2 ≤ 2 ^ n := by + induction n, hn using Nat.le_induction with + | base => norm_num + | succ n hn ih => + calc + (n + 1) ^ 2 ≤ 2 * n ^ 2 := by nlinarith + _ ≤ 2 * 2 ^ n := Nat.mul_le_mul_left _ ih + _ = 2 ^ (n + 1) := by rw [pow_succ]; omega + +/-- An explicit threshold beyond which every fixed affine function of binary size +is bounded by the number itself. -/ +theorem linear_size_le_of_ge (A B : ℕ) {r : ℕ} + (hr : 2 ^ (A + B + 4) ≤ r) : A * Nat.size r + B ≤ r := by + have hs : A + B + 4 < Nat.size r := Nat.lt_size.mpr hr + let t := Nat.size r - 1 + have ht : t + 1 = Nat.size r := by dsimp [t]; omega + have ht4 : 4 ≤ t := by dsimp [t]; omega + have hAB : A + B ≤ t := by omega + have hA : A + 1 ≤ t := by omega + have hpow : 2 ^ t ≤ r := Nat.lt_size.mp (by omega : t < Nat.size r) + calc + A * Nat.size r + B = A * (t + 1) + B := by rw [ht] + _ ≤ t ^ 2 := by nlinarith [Nat.mul_le_mul_right t hA] + _ ≤ 2 ^ t := sq_le_two_pow ht4 + _ ≤ r := hpow + +/-- Binary description length is eventually negligible compared with any rank budget. -/ +theorem eventually_linear_size_le (A B : ℕ) : + ∀ᶠ r : ℕ in atTop, A * Nat.size r + B ≤ r := + (eventually_ge_atTop (2 ^ (A + B + 4))).mono fun _ hr => linear_size_le_of_ge A B hr + +/-- Uniformly over all inputs of an affine binary-size bound, the concrete compiler +eventually meets the affine-description test's rank requirement. -/ +theorem eventually_programFor_length_budget (e : Nat.Partrec.Code) (k b level : ℕ) : + ∀ᶠ r : ℕ in atTop, ∀ n : ℕ, Nat.size n ≤ k * Nat.size r + b → + 2 * (programFor e n).length + level + 1 ≤ r := by + filter_upwards [eventually_linear_size_le (4 * k) + (4 * Nat.size (Encodable.encode e) + 4 * b + level + 1)] with r hr + intro n hn + have hlen := programFor_length_le e n + nlinarith + +/-- Polynomially bounded numerical advice fits the rank budget, uniformly in the advice. -/ +theorem eventually_programFor_bounded_pow_length_budget + (e : Nat.Partrec.Code) (k level : ℕ) : + ∀ᶠ r : ℕ in atTop, ∀ n : ℕ, n ≤ r ^ k → + 2 * (programFor e n).length + level + 1 ≤ r := by + filter_upwards [eventually_programFor_length_budget e k 1 level] with r hr + intro n hn + exact hr n ((Nat.size_le_size hn).trans (size_pow_le r k)) + +/-- In particular, a polynomial input to a fixed algorithm has a sufficiently +short program for every fixed test level once the rank is large enough. -/ +theorem eventually_programFor_pow_length_budget (e : Nat.Partrec.Code) (k level : ℕ) : + ∀ᶠ r : ℕ in atTop, 2 * (programFor e (r ^ k)).length + level + 1 ≤ r := + (eventually_programFor_bounded_pow_length_budget e k level).mono fun r hr => + hr (r ^ k) le_rfl + +/-- A stage parameter can be accompanied by any polynomially bounded advice +index. Encoding the parameter/advice pair still meets the same eventual budget. -/ +theorem eventually_programFor_pair_advice_length_budget + (e : Nat.Partrec.Code) (k level : ℕ) : + ∀ᶠ r : ℕ in atTop, ∀ q : ℕ, q ≤ r ^ k → + 2 * (programFor e (Nat.pair r q)).length + level + 1 ≤ r := by + filter_upwards [eventually_programFor_length_budget e (2 * (k + 1)) 2 level] + with r hr + intro q hq + apply hr + have hs := size_pair_le r q + have hqsize := (Nat.size_le_size hq).trans (size_pow_le r k) + have hmax : max (Nat.size r) (Nat.size q) ≤ Nat.size r + Nat.size q := by omega + nlinarith + +end Klr.AffineProgramLength diff --git a/LeanPool/KLRandomness/BaseFour.lean b/LeanPool/KLRandomness/BaseFour.lean new file mode 100644 index 0000000000..5f6b0f312b --- /dev/null +++ b/LeanPool/KLRandomness/BaseFour.lean @@ -0,0 +1,521 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.PairRespecting +public import LeanPool.KLRandomness.ComputableRational +public import Mathlib.Data.List.GetD +import Mathlib.Tactic.Linarith +import Mathlib.Tactic.NormNum +import Mathlib.Tactic.Ring + +/-! +# Base-four betting and paired binary betting + +The four symbols are represented explicitly by pairs of bits. A base-four +strategy reads one whole digit at a time; its fair capital averages over all +four possible answers. Both simulation directions preserve uniform computable +real capital and success. +-/ + +@[expose] public section + +namespace Klr.BaseFour + +/-- A four-symbol digit represented by its high and low bits. -/ +abbrev Digit := Bool × Bool +/-- An infinite sequence of four-symbol digits. -/ +abbrev Stream := ℕ → Digit + +/-- The base-four digits obtained by grouping adjacent binary coordinates. -/ +def pairDigits (X : Cantor) : Stream := fun n => (X (2 * n), X (2 * n + 1)) + +/-- Flatten a finite digit transcript to its consecutive binary answers. -/ +def unpack : List Digit → List Bool + | [] => [] + | d :: v => d.1 :: d.2 :: unpack v + +/-- Group consecutive answers; an unfinished last digit is omitted. -/ +def pack : List Bool → List Digit + | a :: b :: v => (a, b) :: pack v + | _ => [] + +@[simp] theorem unpack_nil : unpack [] = [] := rfl +@[simp] theorem unpack_cons (d : Digit) (v : List Digit) : + unpack (d :: v) = d.1 :: d.2 :: unpack v := rfl +@[simp] theorem pack_nil : pack [] = [] := rfl +@[simp] theorem pack_singleton (b : Bool) : pack [b] = [] := rfl +@[simp] theorem pack_cons_cons (a b : Bool) (v : List Bool) : + pack (a :: b :: v) = (a, b) :: pack v := rfl + +@[simp] theorem length_unpack (v : List Digit) : (unpack v).length = 2 * v.length := by + induction v with + | nil => rfl + | cons d v ih => simp only [unpack_cons, List.length_cons, ih]; omega + +@[simp] theorem length_pack (v : List Bool) : (pack v).length = v.length / 2 := by + match v with + | [] => rfl + | [a] => simp + | a :: b :: v => + have ih := length_pack v + simp only [pack_cons_cons, List.length_cons, ih] + omega + +theorem unpack_append (v w : List Digit) : unpack (v ++ w) = unpack v ++ unpack w := by + induction v with + | nil => rfl + | cons d v ih => simp [ih] + +@[simp] theorem unpack_snoc (v : List Digit) (d : Digit) : + unpack (v ++ [d]) = unpack v ++ [d.1, d.2] := by + rw [unpack_append] + rfl + +@[simp] theorem pack_unpack (v : List Digit) : pack (unpack v) = v := by + induction v with + | nil => rfl + | cons d v ih => cases d; simp only [unpack_cons, pack_cons_cons, ih] + +@[simp] theorem pack_unpack_snoc (v : List Digit) (b : Bool) : + pack (unpack v ++ [b]) = v := by + induction v with + | nil => rfl + | cons d v ih => + rcases d with ⟨a, c⟩ + simpa using congrArg (List.cons (a, c)) ih + +@[simp] theorem pack_unpack_two (v : List Digit) (a b : Bool) : + pack (unpack v ++ [a, b]) = v ++ [(a, b)] := by + rw [← unpack_snoc v (a, b), pack_unpack] + +theorem take_unpack (v : List Digit) (n : ℕ) : + (unpack v).take (2 * n) = unpack (v.take n) := by + induction v generalizing n with + | nil => simp + | cons d v ih => + cases n with + | zero => rfl + | succ n => + rw [show 2 * (n + 1) = 2 * n + 1 + 1 by omega] + simp [ih] + +theorem pack_take (v : List Bool) (n : ℕ) : + pack (v.take n) = (pack v).take (n / 2) := by + match v with + | [] => simp + | [a] => + cases n <;> simp + | a :: b :: v => + cases n with + | zero => rfl + | succ n => + cases n with + | zero => rfl + | succ n => + have ih := pack_take v n + rw [show (n + 1 + 1) / 2 = n / 2 + 1 by omega] + simpa using congrArg (List.cons (a, b)) ih + +/-- Every binary transcript consists of complete digits and at most one +additional answer. -/ +theorem unpack_cases (v : List Bool) : + (∃ w, v = unpack w) ∨ (∃ w b, v = unpack w ++ [b]) := by + match v with + | [] => exact Or.inl ⟨[], rfl⟩ + | [a] => exact Or.inr ⟨[], a, rfl⟩ + | a :: b :: v => + rcases unpack_cases v with ⟨w, rfl⟩ | ⟨w, c, rfl⟩ + · exact Or.inl ⟨(a, b) :: w, rfl⟩ + · exact Or.inr ⟨(a, b) :: w, c, rfl⟩ + +private def packState : List Bool → List Digit × List Digit + | [] => ([], []) + | a :: v => + (cond (decide (v.length = 0)) [] ((a, v.getD 0 false) :: (packState v).2), + (packState v).1) + +private theorem packState_eq (v : List Bool) : + packState v = (pack v, pack v.tail) := by + induction v with + | nil => rfl + | cons a v ih => + rw [packState, ih] + cases v <;> simp [pack] + +private theorem primrec_packState : Primrec packState := by + let α := List Bool × (Bool × List Bool × (List Digit × List Digit)) + have ha : Primrec (fun p : α => p.2.1) := Primrec.fst.comp Primrec.snd + have hv : Primrec (fun p : α => p.2.2.1) := + Primrec.fst.comp (Primrec.snd.comp Primrec.snd) + have hl : Primrec (fun p : α => p.2.2.2.1) := + Primrec.fst.comp (Primrec.snd.comp (Primrec.snd.comp Primrec.snd)) + have hr : Primrec (fun p : α => p.2.2.2.2) := + Primrec.snd.comp (Primrec.snd.comp (Primrec.snd.comp Primrec.snd)) + have he := Primrec.eq.decide.comp (Primrec.list_length.comp hv) (Primrec.const 0) + have hb := (Primrec.list_getD false).comp hv (Primrec.const 0) + have hd := Primrec.list_cons.comp (ha.pair hb) hr + have hh := ((Primrec.cond he (Primrec.const []) hd).pair hl).to₂ + apply (Primrec.list_rec Primrec.id (Primrec.const ([], [])) hh).of_eq + intro v + induction v with + | nil => rfl + | cons a v ih => + dsimp only [id_eq, List.recOn] at ih + simp only [id_eq, packState, ih] + +theorem computable_pack : Computable pack := + (Primrec.fst.comp primrec_packState).to_comp.of_eq + (fun v => by rw [packState_eq]) + +theorem computable_unpack : Computable unpack := by + have h₁ : Primrec (fun p : List Digit × (Digit × List Bool) => p.2.1.1) := + Primrec.fst.comp (Primrec.fst.comp Primrec.snd) + have h₂ : Primrec (fun p : List Digit × (Digit × List Bool) => p.2.1.2) := + Primrec.snd.comp (Primrec.fst.comp Primrec.snd) + have ht : Primrec (fun p : List Digit × (Digit × List Bool) => p.2.2) := + Primrec.snd.comp Primrec.snd + have hh := (Primrec.list_cons.comp h₁ (Primrec.list_cons.comp h₂ ht)).to₂ + apply (Primrec.list_foldr Primrec.id (Primrec.const []) hh).to_comp.of_eq + intro v + induction v with + | nil => rfl + | cons d v ih => + dsimp only [id_eq] at ih + simp only [id_eq, List.foldr_cons, ih, unpack_cons] + +/-- Last answer of a binary transcript, with zero for the empty transcript. -/ +def lastBit (v : List Bool) : Bool := v.getD (v.length - 1) false + +theorem computable_lastBit : Computable lastBit := + (Primrec.list_getD false).to_comp.comp Computable.id + (Primrec.nat_sub.to_comp.comp Computable.list_length (Computable.const 1)) + +@[simp] theorem lastBit_snoc (v : List Bool) (b : Bool) : + lastBit (v ++ [b]) = b := by + simp only [lastBit, List.length_append, List.length_singleton, Nat.add_sub_cancel] + rw [List.getD_append_right _ _ _ _ (le_refl _)] + simp + +/-- Uniform real computability on finite four-symbol transcripts. -/ +def ComputableRealCapital (d : List Digit → ℝ) : Prop := + ∃ q : List Digit → ℕ → ℚ, + Computable (fun p : List Digit × ℕ => ((q p.1 p.2).num, (q p.1 p.2).den)) ∧ + ∀ v n, |(q v n : ℝ) - d v| ≤ (1 / 2 : ℝ) ^ n + +/-- A computable adaptive query rule that never repeats a digit position along a branch. -/ +structure ScanRule where + /-- Position of the next digit to read after a finite transcript. -/ + query : List Digit → ℕ + computable_query : Computable query + fresh : ∀ (v : List Digit) (n : ℕ), n < v.length → query (v.take n) ≠ query v + +namespace ScanRule + +/-- Digit answers observed through the given number of queries. -/ +def transcript (π : ScanRule) (X : Stream) : ℕ → List Digit + | 0 => [] + | n + 1 => + let v := transcript π X n + v ++ [X (π.query v)] + +@[simp] theorem transcript_zero (π : ScanRule) (X : Stream) : + π.transcript X 0 = [] := rfl + +@[simp] theorem transcript_succ (π : ScanRule) (X : Stream) (n : ℕ) : + π.transcript X (n + 1) = + π.transcript X n ++ [X (π.query (π.transcript X n))] := rfl + +@[simp] theorem length_transcript (π : ScanRule) (X : Stream) (n : ℕ) : + (π.transcript X n).length = n := by + induction n with + | zero => rfl + | succ n ih => simp [ih] + +/-- Read each digit query as two consecutive bit queries. -/ +def toBinary (π : ScanRule) : Klr.ScanRule where + query v := 2 * π.query (pack v) + v.length % 2 + computable_query := + Primrec.nat_add.to_comp.comp + (Primrec.nat_mul.to_comp.comp (Computable.const 2) + (π.computable_query.comp computable_pack)) + (Primrec.nat_mod.to_comp.comp Computable.list_length (Computable.const 2)) + fresh := by + intro v n hn he + simp only [List.length_take, Nat.min_eq_left hn.le, pack_take] at he + have hq : π.query ((pack v).take (n / 2)) = π.query (pack v) := by omega + have hl : n / 2 < (pack v).length := by rw [length_pack]; omega + exact π.fresh (pack v) (n / 2) hl hq + +@[simp] theorem toBinary_query_unpack (π : ScanRule) (v : List Digit) : + π.toBinary.query (unpack v) = 2 * π.query v := by + simp [toBinary] + +@[simp] theorem toBinary_query_unpack_snoc (π : ScanRule) (v : List Digit) (b : Bool) : + π.toBinary.query (unpack v ++ [b]) = 2 * π.query v + 1 := by + simp [toBinary, Nat.add_mod] + +theorem toBinary_pairRespecting (π : ScanRule) : π.toBinary.PairRespecting := by + intro v hv + rcases unpack_cases v with ⟨w, rfl⟩ | ⟨w, b, rfl⟩ + · simp + · simp [Nat.add_mod] at hv + +theorem toBinary_transcript (π : ScanRule) (X : Cantor) (n : ℕ) : + π.toBinary.transcript X (2 * n) = unpack (π.transcript (pairDigits X) n) := by + induction n with + | zero => rfl + | succ n ih => + rw [show 2 * (n + 1) = (2 * n + 1) + 1 by omega] + rw [Klr.ScanRule.transcript_succ, Klr.ScanRule.transcript_succ, ih] + simp [transcript_succ, pairDigits, List.append_assoc] + +end ScanRule + +/-- A pair-respecting binary scan induces a fresh scan of the digit positions. -/ +def ofBinaryScan (π : Klr.ScanRule) (hπ : π.PairRespecting) : ScanRule where + query v := π.query (unpack v) / 2 + computable_query := Primrec.nat_div.to_comp.comp + (π.computable_query.comp computable_unpack) (Computable.const 2) + fresh := by + intro v n hn he + have h₁ := (hπ (unpack (v.take n)) (by simp)).1 + have h₂ := (hπ (unpack v) (by simp)).1 + have hq : π.query (unpack (v.take n)) = π.query (unpack v) := by omega + have hl : 2 * n < (unpack v).length := by simp; omega + apply π.fresh (unpack v) (2 * n) hl + simpa only [take_unpack] using hq + +theorem ofBinaryScan_transcript (π : Klr.ScanRule) (hπ : π.PairRespecting) + (X : Cantor) (n : ℕ) : + π.transcript X (2 * n) = unpack ((ofBinaryScan π hπ).transcript (pairDigits X) n) := by + induction n with + | zero => rfl + | succ n ih => + let v := (ofBinaryScan π hπ).transcript (pairDigits X) n + have he := (hπ (unpack v) (by simp)).1 + have hq : 2 * (π.query (unpack v) / 2) = π.query (unpack v) := by omega + have hp := (hπ (unpack v) (by simp)).2 (X (π.query (unpack v))) + rw [show 2 * (n + 1) = (2 * n + 1) + 1 by omega] + rw [Klr.ScanRule.transcript_succ, Klr.ScanRule.transcript_succ, ih] + change unpack v ++ [X (π.query (unpack v))] ++ + [X (π.query (unpack v ++ [X (π.query (unpack v))]))] = _ + rw [hp] + simp only [ScanRule.transcript_succ, unpack_snoc, pairDigits, ofBinaryScan] + change unpack v ++ [X (π.query (unpack v))] ++ [X (π.query (unpack v) + 1)] = + unpack v ++ [X (2 * (π.query (unpack v) / 2)), + X (2 * (π.query (unpack v) / 2) + 1)] + rw [hq] + simp [List.append_assoc] + +/-- A nonnegative fair capital process on four-symbol transcripts, starting at one. -/ +structure CapitalProcess where + /-- Capital after observing a finite digit transcript. -/ + value : List Digit → ℝ + initial : value [] = 1 + nonneg : ∀ v, 0 ≤ value v + fair : ∀ v, + value (v ++ [(false, false)]) + value (v ++ [(false, true)]) + + value (v ++ [(true, false)]) + value (v ++ [(true, true)]) = 4 * value v + +/-- Conditional expectation after seeing the first bit of a digit. -/ +def splitValue {α : Type*} [DivisionRing α] (d : List Digit → α) (v : List Bool) : α := + if v.length % 2 = 0 then d (pack v) + else (d (pack v ++ [(lastBit v, false)]) + d (pack v ++ [(lastBit v, true)])) / 2 + +@[simp] theorem splitValue_unpack {α : Type*} [DivisionRing α] + (d : List Digit → α) (v : List Digit) : splitValue d (unpack v) = d v := by + simp [splitValue] + +@[simp] theorem splitValue_unpack_snoc {α : Type*} [DivisionRing α] + (d : List Digit → α) (v : List Digit) (b : Bool) : + splitValue d (unpack v ++ [b]) = + (d (v ++ [(b, false)]) + d (v ++ [(b, true)])) / 2 := by + simp [splitValue, Nat.add_mod] + +@[simp] theorem splitValue_unpack_two {α : Type*} [DivisionRing α] + (d : List Digit → α) (v : List Digit) (a b : Bool) : + splitValue d (unpack v ++ [a, b]) = d (v ++ [(a, b)]) := by + rw [← unpack_snoc v (a, b), splitValue_unpack] + +private theorem computable_splitValue {q : List Digit → ℕ → ℚ} + (hq : Computable (fun p : List Digit × ℕ => q p.1 p.2)) : + Computable (fun p : List Bool × ℕ => splitValue (fun v => q v p.2) p.1) := by + have hfst := Computable.fst (α := List Bool) (β := ℕ) + have hsnd := Computable.snd (α := List Bool) (β := ℕ) + have hp := computable_pack.comp hfst + have hb := computable_lastBit.comp hfst + have h₀ := hq.comp ((Computable.list_concat.comp hp + (hb.pair (Computable.const false))).pair hsnd) + have h₁ := hq.comp ((Computable.list_concat.comp hp + (hb.pair (Computable.const true))).pair hsnd) + have hh := RationalComputability.primrec_rat_div.to_comp.comp + (RationalComputability.primrec_rat_add.to_comp.comp h₀ h₁) (Computable.const 2) + have he := Primrec.eq.decide.to_comp.comp + (Primrec.nat_mod.to_comp.comp (Computable.list_length.comp hfst) + (Computable.const 2)) (Computable.const 0) + have h := Computable.cond he (hq.comp (hp.pair hsnd)) hh + exact h.of_eq (fun p => by simp [splitValue, Bool.cond_eq_ite]) + +theorem ComputableRealCapital.toBinary {d : List Digit → ℝ} + (hd : ComputableRealCapital d) : Klr.ComputableRealCapital (splitValue d) := by + obtain ⟨q, hq, herr⟩ := hd + refine ⟨fun v n => splitValue (fun w => q w n) v, ?_, ?_⟩ + · exact RationalComputability.primrec_rat_numDen.to_comp.comp + (computable_splitValue (RationalComputability.computable_rat_of_numDen hq)) + · intro v n + by_cases hv : v.length % 2 = 0 + · simpa only [splitValue, ite_eq_left hv] using herr (pack v) n + · have h₀ := abs_le.mp (herr (pack v ++ [(lastBit v, false)]) n) + have h₁ := abs_le.mp (herr (pack v ++ [(lastBit v, true)]) n) + simp only [splitValue, ite_eq_right hv] + push_cast + rw [abs_le] + constructor <;> linarith + +namespace CapitalProcess + +/-- Splitting a four-way fair bet into its two binary conditional bets. -/ +noncomputable def toBinary (d : CapitalProcess) : Klr.CapitalProcess where + value := splitValue d.value + initial := by simpa [splitValue] using d.initial + nonneg := by + intro v + unfold splitValue + split_ifs + · exact d.nonneg _ + · exact div_nonneg (add_nonneg (d.nonneg _) (d.nonneg _)) (by norm_num) + fair := by + intro v + rcases unpack_cases v with ⟨w, rfl⟩ | ⟨w, b, rfl⟩ + · simp only [splitValue_unpack_snoc, splitValue_unpack] + linarith [d.fair w] + · simp only [List.append_assoc, List.cons_append, List.nil_append, + splitValue_unpack_two, splitValue_unpack_snoc] + ring + +@[simp] theorem toBinary_value_unpack (d : CapitalProcess) (v : List Digit) : + d.toBinary.value (unpack v) = d.value v := splitValue_unpack _ _ + +end CapitalProcess + +/-- Restrict a binary capital process to complete digit transcripts. -/ +noncomputable def ofBinaryCapital (d : Klr.CapitalProcess) : CapitalProcess where + value v := d.value (unpack v) + initial := d.initial + nonneg v := d.nonneg _ + fair := by + intro v + have h := d.fair (unpack v) + have h₀ := d.fair (unpack v ++ [false]) + have h₁ := d.fair (unpack v ++ [true]) + simp only [unpack_snoc] + simp only [List.append_assoc, List.cons_append, List.nil_append] at h₀ h₁ + linarith + +theorem computableRealCapital_ofBinary {d : List Bool → ℝ} + (hd : Klr.ComputableRealCapital d) : + ComputableRealCapital (fun v => d (unpack v)) := by + obtain ⟨q, hq, herr⟩ := hd + refine ⟨fun v n => q (unpack v) n, ?_, fun v n => herr (unpack v) n⟩ + have hp := (computable_unpack.comp (Computable.fst (α := List Digit) (β := ℕ))).pair + (Computable.snd (α := List Digit) (β := ℕ)) + have h := hq.comp hp + exact h + +/-- A total adaptive four-symbol scan with uniformly computable fair capital. -/ +structure BettingStrategy where + /-- The rule choosing which digit position to inspect next. -/ + scan : ScanRule + /-- The capital process on digit transcripts. -/ + capital : CapitalProcess + computable_capital : ComputableRealCapital capital.value + +/-- Success means capital is unbounded along the observed digit transcript. -/ +def BettingStrategy.Succeeds (s : BettingStrategy) (X : Stream) : Prop := + ∀ bound : ℝ, ∃ n, bound < s.capital.value (s.scan.transcript X n) + +/-- A stream on which every total computable-real four-symbol strategy has bounded capital. -/ +def KolmogorovLovelandRandom (X : Stream) : Prop := + ∀ s : BettingStrategy, ¬ s.Succeeds X + +namespace BettingStrategy + +/-- Simulate a four-way bet by two successive binary bets on an adjacent pair. -/ +noncomputable def toBinary (s : BettingStrategy) : Klr.BettingStrategy where + scan := s.scan.toBinary + capital := s.capital.toBinary + computable_capital := s.computable_capital.toBinary + +theorem toBinary_pairRespecting (s : BettingStrategy) : s.toBinary.PairRespecting := + s.scan.toBinary_pairRespecting + +theorem toBinary_preserves_success (s : BettingStrategy) {X : Cantor} + (hs : s.Succeeds (pairDigits X)) : s.toBinary.Succeeds X := by + intro bound + obtain ⟨n, hn⟩ := hs bound + refine ⟨2 * n, ?_⟩ + change bound < s.capital.toBinary.value (s.scan.toBinary.transcript X (2 * n)) + simpa only [ScanRule.toBinary_transcript, CapitalProcess.toBinary_value_unpack] using hn + +end BettingStrategy + +/-- Restrict a pair-respecting binary strategy to times when whole pairs have been read. -/ +noncomputable def ofBinary (s : Klr.BettingStrategy) (hs : s.PairRespecting) : BettingStrategy where + scan := ofBinaryScan s.scan hs + capital := ofBinaryCapital s.capital + computable_capital := computableRealCapital_ofBinary s.computable_capital + +/-- A binary capital process can grow by at most a factor of two between +successive complete digits. -/ +theorem binary_succeeds_iff_even (s : Klr.BettingStrategy) (X : Cantor) : + s.Succeeds X ↔ ∀ bound : ℝ, ∃ n, + bound < s.capital.value (s.scan.transcript X (2 * n)) := by + constructor + · intro hs bound + obtain ⟨t, ht⟩ := hs (2 * max bound 0) + refine ⟨t / 2, ?_⟩ + have hmax := le_max_left bound (0 : ℝ) + have hnonneg := le_max_right bound (0 : ℝ) + by_cases he : t % 2 = 0 + · have ht' : t = 2 * (t / 2) := by omega + rw [ht'] at ht + linarith + · have ht' : t = 2 * (t / 2) + 1 := by omega + rw [ht', Klr.ScanRule.transcript_succ] at ht + have hc := s.capital.successor_le (s.scan.transcript X (2 * (t / 2))) + (X (s.scan.query (s.scan.transcript X (2 * (t / 2))))) + linarith + · intro hs bound + obtain ⟨n, hn⟩ := hs bound + exact ⟨2 * n, hn⟩ + +theorem ofBinary_succeeds_iff (s : Klr.BettingStrategy) (hs : s.PairRespecting) (X : Cantor) : + (ofBinary s hs).Succeeds (pairDigits X) ↔ s.Succeeds X := by + rw [binary_succeeds_iff_even] + change (∀ bound : ℝ, ∃ n, + bound < s.capital.value (unpack ((ofBinaryScan s.scan hs).transcript (pairDigits X) n))) ↔ _ + simp only [ofBinaryScan_transcript s.scan hs X] + +/-- Four-symbol KL randomness is exactly resistance to pair-respecting binary +strategies. Both sides use total fresh scans and uniformly computable real capital. -/ +theorem kolmogorovLovelandRandom_pairDigits_iff (X : Cantor) : + KolmogorovLovelandRandom (pairDigits X) ↔ Klr.PairRespectingRandom X := by + constructor + · intro hX s hs hsucc + exact hX (ofBinary s hs) ((ofBinary_succeeds_iff s hs X).mpr hsucc) + · intro hX s hsucc + exact hX s.toBinary s.toBinary_pairRespecting (s.toBinary_preserves_success hsucc) + +/-- Grouping binary digits into pairs preserves KL randomness. -/ +theorem of_binary_kolmogorovLovelandRandom {X : Cantor} + (hX : Klr.KolmogorovLovelandRandom X) : KolmogorovLovelandRandom (pairDigits X) := + (kolmogorovLovelandRandom_pairDigits_iff X).mpr hX.pairRespectingRandom + +end Klr.BaseFour diff --git a/LeanPool/KLRandomness/BaseInvariance.lean b/LeanPool/KLRandomness/BaseInvariance.lean new file mode 100644 index 0000000000..27f5f98172 --- /dev/null +++ b/LeanPool/KLRandomness/BaseInvariance.lean @@ -0,0 +1,48 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.BaseFour +public import LeanPool.KLRandomness.ParityConstruction +public import LeanPool.KLRandomness.Splitting + +/-! +# KL randomness is not invariant under binary/base-four regrouping + +The witness resists every strategy reading whole pairs, but its even and +odd halves both fail Martin-Löf randomness. The proved splitting theorem +therefore rules out binary KL randomness. Both bases use total fresh scans +and uniformly computable real capital, with the appropriate fair averaging. +-/ + +@[expose] public section + +namespace Klr + +/-- A base-four KL-random digit stream whose binary ungrouping is not +KL-random, with the base-four stream displayed as adjacent pairs of bits. -/ +theorem exists_baseFour_random_not_binary_random : + ∃ X : Cantor, BaseFour.KolmogorovLovelandRandom (BaseFour.pairDigits X) ∧ + ¬KolmogorovLovelandRandom X := by + obtain ⟨X, hpair, h0, h1⟩ := + ParityConstruction.exists_pairRespectingRandom_halves_not_martinLofRandom + refine ⟨X, (BaseFour.kolmogorovLovelandRandom_pairDigits_iff X).mpr hpair, ?_⟩ + intro hX + exact (kolmogorovLovelandRandom_even_or_odd X hX).elim h0 h1 + +/-- Binary KL randomness implies base-four KL randomness, and the converse +fails for the canonical grouping of adjacent bits. -/ +theorem binary_random_ssubset_baseFour_random : + {X : Cantor | KolmogorovLovelandRandom X} ⊂ + {X : Cantor | BaseFour.KolmogorovLovelandRandom (BaseFour.pairDigits X)} := by + apply Set.ssubset_iff_exists.mpr + refine ⟨fun _ hX => BaseFour.of_binary_kolmogorovLovelandRandom hX, ?_⟩ + exact exists_baseFour_random_not_binary_random + +end Klr diff --git a/LeanPool/KLRandomness/Betting.lean b/LeanPool/KLRandomness/Betting.lean new file mode 100644 index 0000000000..1e0cc7fdb7 --- /dev/null +++ b/LeanPool/KLRandomness/Betting.lean @@ -0,0 +1,208 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.Cantor +public import Mathlib.Computability.Partrec +public import Mathlib.Data.Rat.Cast.Order +import Mathlib.Tactic.FieldSimp +import Mathlib.Tactic.Linarith +import Mathlib.Tactic.Positivity + +/-! +# Total nonmonotonic betting strategies + +These definitions follow Section 2 of Liu and Meng, arXiv:2611.31004v1. +The capital can be a computable real, rather than just a rational number. +Computability is witnessed by uniform rational approximations, encoded by +their integer numerator and natural denominator. + +The definition of KL randomness here uses total strategies, as in the paper. +`PartialBettingCapital` proves totalization for partial rational-wager programs. +The bridge from general partial computable-real capital remains separate. +-/ + +@[expose] public section + +namespace Klr + +/-- Uniform computability of a real-valued function on finite bit strings. +The rate of approximation is fixed, so mere pointwise computability does not +suffice. Rational numbers use their canonical numerator/denominator coding. -/ +def ComputableRealCapital (d : List Bool → ℝ) : Prop := + ∃ q : List Bool → ℕ → ℚ, + Computable (fun p : List Bool × ℕ => ((q p.1 p.2).num, (q p.1 p.2).den)) ∧ + ∀ v n, |(q v n : ℝ) - d v| ≤ (1 / 2 : ℝ) ^ n + +/-- A total computable query rule, with no repeated query on a branch. +Freshness is imposed on every finite transcript, including transcripts not +generated by a particular input. -/ +structure ScanRule where + /-- Position of the next input bit after a finite transcript. -/ + query : List Bool → ℕ + computable_query : Computable query + fresh : ∀ (v : List Bool) (n : ℕ), n < v.length → query (v.take n) ≠ query v + +namespace ScanRule + +/-- The answers actually observed by a scan rule on input `X`. -/ +def transcript (π : ScanRule) (X : Cantor) : ℕ → List Bool + | 0 => [] + | n + 1 => + let v := transcript π X n + v ++ [X (π.query v)] + +@[simp] theorem transcript_zero (π : ScanRule) (X : Cantor) : + π.transcript X 0 = [] := rfl + +@[simp] theorem transcript_succ (π : ScanRule) (X : Cantor) (n : ℕ) : + π.transcript X (n + 1) = + π.transcript X n ++ [X (π.query (π.transcript X n))] := rfl + +@[simp] theorem length_transcript (π : ScanRule) (X : Cantor) (n : ℕ) : + (π.transcript X n).length = n := by + induction n with + | zero => rfl + | succ n ih => simp [ih] + +theorem transcript_prefix (π : ScanRule) (X : Cantor) {m n : ℕ} (h : m ≤ n) : + π.transcript X m <+: π.transcript X n := by + induction h with + | refl => exact List.prefix_refl _ + | @step n h ih => + exact ih.trans (List.prefix_append _ _) + +theorem transcript_take (π : ScanRule) (X : Cantor) {m n : ℕ} (h : m ≤ n) : + (π.transcript X n).take m = π.transcript X m := by + obtain ⟨t, ht⟩ := π.transcript_prefix X h + rw [← ht, ← π.length_transcript X m] + simp + +/-- Distinct times query distinct input positions. This is the condition +needed for fair-coin inputs to induce fair-coin transcripts. -/ +theorem query_ne_of_lt (π : ScanRule) (X : Cantor) {m n : ℕ} (h : m < n) : + π.query (π.transcript X m) ≠ π.query (π.transcript X n) := by + have hf := π.fresh (π.transcript X n) m (by simpa using h) + simpa [π.transcript_take X h.le] using hf + +theorem query_injective (π : ScanRule) (X : Cantor) : + Function.Injective (fun n => π.query (π.transcript X n)) := by + intro m n h + rcases lt_trichotomy m n with hlt | heq | hgt + · exact False.elim (π.query_ne_of_lt X hlt h) + · exact heq + · exact False.elim (π.query_ne_of_lt X hgt h.symm) + +/-- Reading input positions in their usual increasing order. -/ +def monotone : ScanRule where + query := List.length + computable_query := Computable.list_length + fresh := by + intro v n hn + simp only [List.length_take, Nat.min_eq_left hn.le] + omega + +/-- The usual prefix of an input, expressed as a list. -/ +def inputPrefix (X : Cantor) (n : ℕ) : List Bool := + (List.range n).map X + +@[simp] theorem monotone_transcript (X : Cantor) (n : ℕ) : + monotone.transcript X n = inputPrefix X n := by + induction n with + | zero => rfl + | succ n ih => + rw [transcript_succ] + change monotone.transcript X n ++ [X (monotone.transcript X n).length] = _ + rw [length_transcript, ih] + simp [inputPrefix, List.range_succ] + +end ScanRule + +/-- A nonnegative fair capital function, with initial capital one. -/ +structure CapitalProcess where + /-- Capital after observing a finite binary transcript. -/ + value : List Bool → ℝ + initial : value [] = 1 + nonneg : ∀ v, 0 ≤ value v + fair : ∀ v, value (v ++ [false]) + value (v ++ [true]) = 2 * value v + +namespace CapitalProcess + +/-- The signed fraction staked on the next answer. At zero capital it is zero +by the convention for division in Lean. -/ +noncomputable def wager (d : CapitalProcess) (v : List Bool) : ℝ := + (d.value (v ++ [true]) - d.value (v ++ [false])) / (2 * d.value v) + +theorem successor_le (d : CapitalProcess) (v : List Bool) (b : Bool) : + d.value (v ++ [b]) ≤ 2 * d.value v := by + have h := d.fair v + have h₀ := d.nonneg (v ++ [false]) + have h₁ := d.nonneg (v ++ [true]) + cases b <;> linarith + +theorem successor_eq_zero (d : CapitalProcess) (v : List Bool) + (hv : d.value v = 0) (b : Bool) : d.value (v ++ [b]) = 0 := by + have h := d.successor_le v b + rw [hv] at h + exact le_antisymm (by linarith) (d.nonneg _) + +theorem abs_wager_le_one (d : CapitalProcess) (v : List Bool) + (hv : 0 < d.value v) : |d.wager v| ≤ 1 := by + have h := d.fair v + have h₀ := d.nonneg (v ++ [false]) + have h₁ := d.nonneg (v ++ [true]) + rw [wager, abs_le] + constructor + · apply (le_div_iff₀ (by positivity : 0 < 2 * d.value v)).2 + linarith + · apply (div_le_iff₀ (by positivity : 0 < 2 * d.value v)).2 + linarith + +theorem update (d : CapitalProcess) (v : List Bool) + (hv : 0 < d.value v) (b : Bool) : + d.value (v ++ [b]) = + d.value v * (1 + (if b then 1 else -1) * d.wager v) := by + have h := d.fair v + have hn : d.value v ≠ 0 := ne_of_gt hv + cases b <;> simp only [Bool.false_eq_true, ite_false, ite_true] <;> + unfold wager <;> field_simp <;> nlinarith + +end CapitalProcess + +/-- A total computable nonmonotonic betting strategy. -/ +structure BettingStrategy where + /-- The adaptive order in which the input bits are read. -/ + scan : ScanRule + /-- The fair capital process associated with the scan. -/ + capital : CapitalProcess + computable_capital : ComputableRealCapital capital.value + +/-- Success means unbounded capital, not convergence to infinity. -/ +def BettingStrategy.Succeeds (s : BettingStrategy) (X : Cantor) : Prop := + ∀ bound : ℝ, ∃ n, bound < s.capital.value (s.scan.transcript X n) + +/-- Kolmogorov–Loveland randomness in the paper's total-strategy formulation. -/ +def KolmogorovLovelandRandom (X : Cantor) : Prop := + ∀ s : BettingStrategy, ¬ s.Succeeds X + +/-- Computable randomness, using the same computable-real capital functions +and ordinary left-to-right scanning. -/ +def ComputablyRandom (X : Cantor) : Prop := + ∀ d : CapitalProcess, ComputableRealCapital d.value → + ¬ (∀ bound : ℝ, ∃ n, bound < d.value (ScanRule.inputPrefix X n)) + +theorem KolmogorovLovelandRandom.computablyRandom {X : Cantor} + (hX : KolmogorovLovelandRandom X) : ComputablyRandom X := by + intro d hd hs + apply hX ⟨ScanRule.monotone, d, hd⟩ + intro bound + obtain ⟨n, hn⟩ := hs bound + exact ⟨n, by simpa using hn⟩ + +end Klr diff --git a/LeanPool/KLRandomness/BlockProduct.lean b/LeanPool/KLRandomness/BlockProduct.lean new file mode 100644 index 0000000000..d0a4ccb8b7 --- /dev/null +++ b/LeanPool/KLRandomness/BlockProduct.lean @@ -0,0 +1,229 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.NoDrop +public import LeanPool.KLRandomness.PrefixStage +public import Mathlib.MeasureTheory.Constructions.KolmogorovExtension + +/-! +# The infinite law of disjoint affine blocks + +Each finite set of input coordinates meets only finitely many disjoint blocks. +Its law is therefore determined by a sufficiently long finite stage. These +finite-coordinate laws form a projective family, from which Mathlib's +Kolmogorov extension construction gives the actual infinite probability law. +No consistency or infinite-law premise is assumed. +-/ + +@[expose] public section + +namespace Klr.BlockProduct + +open MeasureTheory ProbabilityTheory +open scoped ENNReal + +/-- A position belongs to at most one member of a disjoint block family. -/ +theorem index_eq_of_mem (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) + {q i j : ℕ} (hi : q ∈ (B i).support) (hj : q ∈ (B j).support) : i = j := by + by_contra h + exact Finset.disjoint_left.mp (hdis h) hi hj + +/-- One greater than the block owning a coordinate, or zero if the coordinate is free. -/ +noncomputable def coordinateCutoff (B : ℕ → AffineBlock) (q : ℕ) : ℕ := by + classical + exact if h : ∃ k, q ∈ (B k).support then h.choose + 1 else 0 + +theorem coordinateCutoff_of_mem (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) + {q k : ℕ} (hq : q ∈ (B k).support) : coordinateCutoff B q = k + 1 := by + rw [coordinateCutoff, dite_eq_left ⟨k, hq⟩] + exact congrArg (· + 1) (index_eq_of_mem B hdis (q := q) + (Exists.choose_spec (show ∃ i, q ∈ (B i).support from ⟨k, hq⟩)) hq) + +/-- A finite stage containing every block which meets a given finite coordinate set. -/ +noncomputable def cutoff (B : ℕ → AffineBlock) (G : Finset ℕ) : ℕ := + G.sup (coordinateCutoff B) + +@[simp] theorem cutoff_empty (B : ℕ → AffineBlock) : cutoff B ∅ = 0 := rfl + +theorem cutoff_mono (B : ℕ → AffineBlock) {G H : Finset ℕ} (h : G ⊆ H) : + cutoff B G ≤ cutoff B H := Finset.sup_mono h + +theorem index_lt_cutoff_of_mem (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) + {G : Finset ℕ} {q k : ℕ} (hG : q ∈ G) (hB : q ∈ (B k).support) : + k < cutoff B G := by + have h := Finset.le_sup (f := coordinateCutoff B) hG + rw [coordinateCutoff_of_mem B hdis hB] at h + exact Nat.lt_of_succ_le h + +theorem disjoint_of_cutoff_le (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) + (G : Finset ℕ) {k : ℕ} (hk : cutoff B G ≤ k) : Disjoint G (B k).support := by + apply Finset.disjoint_left.mpr + intro q hG hB + exact (not_lt_of_ge hk) (index_lt_cutoff_of_mem B hdis hG hB) + +theorem dependsOn_restrict_preimage (G : Finset ℕ) (S : Set (G → Bool)) : + DependsOn (fun X : Cantor => X ∈ G.restrict ⁻¹' S) (G : Set ℕ) := by + intro X Y hXY + have he : G.restrict X = G.restrict Y := funext fun i => hXY i.val i.property + change (G.restrict X ∈ S) = (G.restrict Y ∈ S) + rw [he] + +theorem exists_restrict_preimage (G : Finset ℕ) (A : Set Cantor) + (hA : DependsOn (fun X : Cantor => X ∈ A) (G : Set ℕ)) : + ∃ S : Set (G → Bool), A = G.restrict ⁻¹' S := by + obtain ⟨P, hP⟩ := dependsOn_iff_exists_comp.mp hA + refine ⟨{x | P x}, ?_⟩ + ext X + exact iff_of_eq (congrFun hP X) + +/-- The finite-coordinate marginal obtained after every block meeting those coordinates +has been imposed. -/ +noncomputable def marginal (B : ℕ → AffineBlock) (G : Finset ℕ) : Measure (G → Bool) := + (PrefixStage.law B (cutoff B G)).map G.restrict + +theorem marginal_isProbabilityMeasure (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) (G : Finset ℕ) : + IsProbabilityMeasure (marginal B G) := by + let : IsProbabilityMeasure (PrefixStage.law B (cutoff B G)) := + PrefixStage.law_isProbabilityMeasure B hdis _ + unfold marginal + infer_instance + +/-- The finite-coordinate laws are consistent. This is proved from disjoint-support +independence of the actual finite stages. -/ +theorem marginal_projective (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) : + IsProjectiveMeasureFamily (α := fun _ : ℕ => Bool) (marginal B) := by + intro I J hJI + ext S hS + change ((PrefixStage.law B (cutoff B J)).map J.restrict) S = + (((PrefixStage.law B (cutoff B I)).map I.restrict).map + (Finset.restrict₂ (π := fun _ : ℕ => Bool) hJI)) S + rw [Measure.map_map (Finset.measurable_restrict₂ (X := fun _ : ℕ => Bool) hJI) + I.measurable_restrict, + Measure.map_apply J.measurable_restrict hS, + Measure.map_apply ((Finset.measurable_restrict₂ (X := fun _ : ℕ => Bool) hJI).comp + I.measurable_restrict) hS] + change PrefixStage.law B (cutoff B J) (J.restrict ⁻¹' S) = + PrefixStage.law B (cutoff B I) (J.restrict ⁻¹' S) + exact (PrefixStage.law_apply_eq_of_disjoint B hdis (cutoff_mono B hJI) + J (J.restrict ⁻¹' S) (dependsOn_restrict_preimage J S) + (fun k hk _ => disjoint_of_cutoff_le B hdis J hk)).symm + +/-- The actual infinite law of independent uniform affine-block solutions and fair free +coordinates, constructed from its proved coherent finite-stage marginals. -/ +noncomputable def law (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) : Measure Cantor := by + let _ : ∀ G, IsProbabilityMeasure (marginal B G) := marginal_isProbabilityMeasure B hdis + exact projectiveLimit (α := fun _ : ℕ => Bool) (marginal B) (marginal_projective B hdis) + +instance law_isProbabilityMeasure (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) : + IsProbabilityMeasure (law B hdis) := by + let : ∀ G, IsProbabilityMeasure (marginal B G) := marginal_isProbabilityMeasure B hdis + unfold law + infer_instance + +theorem law_isProjectiveLimit (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) : + IsProjectiveLimit (law B hdis) (marginal B) := by + let : ∀ G, IsProbabilityMeasure (marginal B G) := marginal_isProbabilityMeasure B hdis + exact isProjectiveLimit_projectiveLimit (marginal_projective B hdis) + +/-- Exact finite-coordinate marginals of the constructed infinite law. -/ +theorem law_map_restrict (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) (G : Finset ℕ) : + (law B hdis).map G.restrict = marginal B G := + law_isProjectiveLimit B hdis G + +/-- Every event on finitely many coordinates has exactly its stabilized finite-stage mass. -/ +theorem law_apply_eq_cutoff (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) + (G : Finset ℕ) (A : Set Cantor) + (hA : DependsOn (fun X : Cantor => X ∈ A) (G : Set ℕ)) : + law B hdis A = PrefixStage.law B (cutoff B G) A := by + obtain ⟨S, rfl⟩ := exists_restrict_preimage G A hA + rw [← Measure.map_apply G.measurable_restrict S.toFinite.measurableSet, + law_map_restrict, marginal, + Measure.map_apply G.measurable_restrict S.toFinite.measurableSet] + +/-- Any sufficiently late finite stage already has the final law on a finite set of coordinates. -/ +theorem law_apply_eq_stage (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) + (G : Finset ℕ) (A : Set Cantor) + (hA : DependsOn (fun X : Cantor => X ∈ A) (G : Set ℕ)) + (n : ℕ) (hn : cutoff B G ≤ n) : law B hdis A = PrefixStage.law B n A := by + rw [law_apply_eq_cutoff B hdis G A hA] + exact (PrefixStage.law_apply_eq_of_disjoint B hdis hn G A hA + (fun k hk _ => disjoint_of_cutoff_le B hdis G hk)).symm + +/-- Every individual block equation holds with probability one under the infinite law. -/ +theorem law_block_event (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) (k : ℕ) : + law B hdis (B k).event = 1 := by + let n := max (cutoff B (B k).support) (k + 1) + rw [law_apply_eq_stage B hdis (B k).support (B k).event (B k).dependsOn_event + n (Nat.le_max_left _ _)] + exact PrefixStage.law_block_event B hdis n k + (lt_of_lt_of_le (Nat.lt_succ_self k) (Nat.le_max_right _ _)) + +/-- The constructed law almost surely satisfies all countably many affine constraints. -/ +theorem ae_all_blocks (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) : + ∀ᵐ X ∂law B hdis, ∀ k, X ∈ (B k).event := by + apply ae_all_iff.mpr + intro k + apply ae_iff.mpr + change law B hdis (B k).eventᶜ = 0 + rw [measure_compl (B k).measurableSet_event (measure_ne_top _ _), + measure_univ, law_block_event, tsub_self] + +/-- The intersection of all block constraints has full measure. -/ +theorem law_familyEvent (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) : + law B hdis (AffineBlock.familyEvent B) = 1 := by + have hc : law B hdis (AffineBlock.familyEvent B)ᶜ = 0 := + ae_iff.mp (ae_all_blocks B hdis) + simpa only [compl_compl, measure_univ, hc, tsub_zero] using + measure_compl (AffineBlock.measurableSet_familyEvent B).compl + (show law B hdis (AffineBlock.familyEvent B)ᶜ ≠ ∞ by rw [hc]; exact ENNReal.zero_ne_top) + +/-- The infinite block law and stage `j` agree on a finite adaptive transcript whenever +every block from `j` onward still has full unread rank after that transcript. -/ +theorem law_inputEvent_eq_of_fullRank (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) + (j : ℕ) (π : ScanRule) (v : List Bool) + (hfull : ∀ k, j ≤ k → (B k).UnreadFullRank π v) : + law B hdis (StoppingTranscript.inputEvent π v) = + PrefixStage.law B j (StoppingTranscript.inputEvent π v) := by + let n := max (cutoff B (π.queriedPositions v)) j + rw [law_apply_eq_stage B hdis (π.queriedPositions v) + (StoppingTranscript.inputEvent π v) (π.dependsOn_inputEvent v) n (Nat.le_max_left _ _)] + exact PrefixStage.law_transcript_eq_of_fullRank B hdis j n (Nat.le_max_right _ _) π v + (fun k hk _ => hfull k hk) + +/-- The infinite/finite comparison also holds for unbounded prefix-free stopping unions, +provided every not-yet-imposed block retains full rank at each stopping transcript. -/ +theorem law_unionEvent_eq_of_fullRank (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) + (j : ℕ) (π : ScanRule) {W : Set (List Bool)} + (hW : StoppingTranscript.PrefixFree W) + (hfull : ∀ v ∈ W, ∀ k, j ≤ k → (B k).UnreadFullRank π v) : + law B hdis (StoppingTranscript.unionEvent π W) = + PrefixStage.law B j (StoppingTranscript.unionEvent π W) := by + apply StoppingTranscript.measure_unionEvent_eq _ _ π hW + intro v hv + exact law_inputEvent_eq_of_fullRank B hdis j π v (hfull v hv) + +end Klr.BlockProduct diff --git a/LeanPool/KLRandomness/BlockProductAnswer.lean b/LeanPool/KLRandomness/BlockProductAnswer.lean new file mode 100644 index 0000000000..d8e5e5e120 --- /dev/null +++ b/LeanPool/KLRandomness/BlockProductAnswer.lean @@ -0,0 +1,294 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.BlockProduct + +/-! +# Fair and forced next answers under the infinite block law + +Parent and child transcript events depend on finitely many coordinates. Their +probabilities under the constructed infinite law therefore agree with one +sufficiently late finite stage. At that stage the affine next-answer theorem +applies, including after partial rank loss. Null parent events are handled by +monotonicity, so the child-mass identities have no compatibility premise. +-/ + +@[expose] public section + +namespace Klr.BlockProductAnswer + +open MeasureTheory ProbabilityTheory AffineAnswer StoppingTranscript +open scoped ENNReal + +/-- A query is forced when its own block loses unread rank at that query. -/ +def forced (B : ℕ → AffineBlock) (π : ScanRule) (v : List Bool) : Prop := + ∃ k, π.query v ∈ (B k).support ∧ + (B k).remainingRank π (v ++ [false]) < (B k).remainingRank π v + +/-- The child transcript also specifies the next queried input bit. -/ +theorem inputEvent_snoc (π : ScanRule) (v : List Bool) (b : Bool) : + inputEvent π (v ++ [b]) = inputEvent π v ∩ bitEvent (π.query v) b := by + ext X + constructor + · intro h + change π.transcript X (v ++ [b]).length = v ++ [b] at h + simp only [List.length_append, List.length_singleton] at h + have ht := π.transcript_take X (m := v.length) (n := v.length + 1) (by omega) + rw [h] at ht + have hp : π.transcript X v.length = v := by simpa using ht.symm + rw [ScanRule.transcript_succ, hp] at h + have hb : X (π.query v) = b := by simpa using List.append_cancel_left h + exact ⟨hp, hb⟩ + · rintro ⟨hp, hb⟩ + change π.transcript X v.length = v at hp + change X (π.query v) = b at hb + simp [inputEvent, ScanRule.transcript_succ, hp, hb] + +theorem inputEvent_snoc_subset (π : ScanRule) (v : List Bool) (b : Bool) : + inputEvent π (v ++ [b]) ⊆ inputEvent π v := by + rw [inputEvent_snoc] + exact Set.inter_subset_left + +/-- A conditional fair-answer identity gives a mass identity even for a null parent. -/ +theorem child_mass_of_cond_fair (μ : Measure Cantor) [IsFiniteMeasure μ] + (π : ScanRule) (v : List Bool) (b : Bool) + (hfair : μ (inputEvent π v) ≠ 0 → + (cond μ (inputEvent π v)) (bitEvent (π.query v) b) = (1 / 2 : ℝ≥0∞)) : + μ (inputEvent π (v ++ [b])) = (1 / 2 : ℝ≥0∞) * μ (inputEvent π v) := by + by_cases hzero : μ (inputEvent π v) = 0 + · rw [measure_mono_null (inputEvent_snoc_subset π v b) hzero, hzero, mul_zero] + · rw [inputEvent_snoc, ← cond_mul_eq_inter (measurableSet_inputEvent π v) + (bitEvent (π.query v) b) μ, hfair hzero] + +/-- Conditional forcing gives an unconditional deterministic split, with both children +null when the parent is null. -/ +theorem child_mass_of_cond_forced (μ : Measure Cantor) [IsFiniteMeasure μ] + (π : ScanRule) (v : List Bool) + (hforce : μ (inputEvent π v) ≠ 0 → ∃ b : Bool, + (cond μ (inputEvent π v)) (bitEvent (π.query v) b) = 1 ∧ + (cond μ (inputEvent π v)) (bitEvent (π.query v) (!b)) = 0) : + ∃ b : Bool, μ (inputEvent π (v ++ [b])) = μ (inputEvent π v) ∧ + μ (inputEvent π (v ++ [!b])) = 0 := by + by_cases hzero : μ (inputEvent π v) = 0 + · refine ⟨false, ?_, ?_⟩ + · rw [measure_mono_null (inputEvent_snoc_subset π v false) hzero, hzero] + · exact measure_mono_null (inputEvent_snoc_subset π v (!false)) hzero + · obtain ⟨b, hb, hnb⟩ := hforce hzero + refine ⟨b, ?_, ?_⟩ + · rw [inputEvent_snoc, ← cond_mul_eq_inter (measurableSet_inputEvent π v) + (bitEvent (π.query v) b) μ, hb, one_mul] + · rw [inputEvent_snoc, ← cond_mul_eq_inter (measurableSet_inputEvent π v) + (bitEvent (π.query v) (!b)) μ, hnb, zero_mul] + +/-- The other members of a finite prefix, with one selected block removed. -/ +def otherPrefix (B : ℕ → AffineBlock) (n k : ℕ) : {i : Fin n // i.val ≠ k} → AffineBlock := + fun i => B i.val.val + +theorem prefixEvent_eq_otherPrefix (B : ℕ → AffineBlock) (n k : ℕ) (hk : k < n) : + PrefixStage.prefixEvent B n = + AffineBlock.familyEvent (otherPrefix B n k) ∩ (B k).event := by + ext X + rw [PrefixStage.mem_prefixEvent] + change (∀ j < n, X ∈ (B j).event) ↔ + (∀ i : {i : Fin n // i.val ≠ k}, X ∈ (B i.val.val).event) ∧ X ∈ (B k).event + constructor + · intro h + exact ⟨fun i => h i.val.val i.val.isLt, h k hk⟩ + · rintro ⟨h, hkX⟩ j hj + by_cases he : j = k + · simpa [he] using hkX + · exact h ⟨⟨j, hj⟩, he⟩ + +private theorem prefix_history_ne_zero (B : ℕ → AffineBlock) (n k : ℕ) (hk : k < n) + (π : ScanRule) (v : List Bool) (h : PrefixStage.law B n (inputEvent π v) ≠ 0) : + fairCoin (history (otherPrefix B n k) (B k) π v) ≠ 0 := by + have hp := inter_pos_of_cond_ne_zero (PrefixStage.measurableSet_prefixEvent B n) h + rw [prefixEvent_eq_otherPrefix B n k hk] at hp + exact hp.ne' + +private theorem prefix_cond_transcript (B : ℕ → AffineBlock) (n k : ℕ) (hk : k < n) + (π : ScanRule) (v : List Bool) : + cond (PrefixStage.law B n) (inputEvent π v) = + cond fairCoin (history (otherPrefix B n k) (B k) π v) := by + rw [PrefixStage.law_eq_cond, prefixEvent_eq_otherPrefix B n k hk] + exact cond_stage_transcript (otherPrefix B n k) (B k) π v + +/-- The finite-prefix child identity, with the queried block isolated from all others. -/ +theorem prefix_child_mass_of_no_rank_drop (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) + (n k : ℕ) (hk : k < n) (π : ScanRule) (v : List Bool) + (hq : π.query v ∈ (B k).support) + (hnodrop : ¬(B k).remainingRank π (v ++ [false]) < (B k).remainingRank π v) (b : Bool) : + PrefixStage.law B n (inputEvent π (v ++ [b])) = + (1 / 2 : ℝ≥0∞) * PrefixStage.law B n (inputEvent π v) := by + let _ := PrefixStage.law_isProbabilityMeasure B hdis n + apply child_mass_of_cond_fair (PrefixStage.law B n) π v b + intro hpos + rw [prefix_cond_transcript B n k hk π v] + exact cond_next_bit_eq_half_of_no_rank_drop (otherPrefix B n k) (B k) + (fun i => hdis i.property) π v hq (prefix_history_ne_zero B n k hk π v hpos) hnodrop b + +/-- The finite-prefix child identity for a query outside every block. -/ +theorem prefix_child_mass_of_free (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) + (n : ℕ) (hn : 0 < n) (π : ScanRule) (v : List Bool) + (hfree : ∀ k, π.query v ∉ (B k).support) (b : Bool) : + PrefixStage.law B n (inputEvent π (v ++ [b])) = + (1 / 2 : ℝ≥0∞) * PrefixStage.law B n (inputEvent π v) := by + let _ := PrefixStage.law_isProbabilityMeasure B hdis n + apply child_mass_of_cond_fair (PrefixStage.law B n) π v b + intro hpos + rw [prefix_cond_transcript B n 0 hn π v] + exact cond_next_bit_eq_half_of_free (otherPrefix B n 0) (B 0) π v + (hfree 0) (fun i => hfree i.val.val) (prefix_history_ne_zero B n 0 hn π v hpos) b + +/-- A strict rank drop gives a deterministic child split at a finite prefix stage. -/ +theorem prefix_child_mass_forced (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) + (n k : ℕ) (hk : k < n) (π : ScanRule) (v : List Bool) + (hq : π.query v ∈ (B k).support) + (hdrop : (B k).remainingRank π (v ++ [false]) < (B k).remainingRank π v) : + ∃ b : Bool, PrefixStage.law B n (inputEvent π (v ++ [b])) = + PrefixStage.law B n (inputEvent π v) ∧ + PrefixStage.law B n (inputEvent π (v ++ [!b])) = 0 := by + let _ := PrefixStage.law_isProbabilityMeasure B hdis n + apply child_mass_of_cond_forced (PrefixStage.law B n) π v + intro hpos + rw [prefix_cond_transcript B n k hk π v] + obtain ⟨b, _, hb, hnb⟩ := cond_next_bit_forced_of_rank_drop + (otherPrefix B n k) (B k) π v hq (prefix_history_ne_zero B n k hk π v hpos) hdrop + exact ⟨b, hb, hnb⟩ + +/-- The finite coordinates needed to distinguish a parent transcript and both its children. -/ +def nextSupport (π : ScanRule) (v : List Bool) : Finset ℕ := + insert (π.query v) (π.queriedPositions v) + +private theorem parent_dependsOn_nextSupport (π : ScanRule) (v : List Bool) : + DependsOn (fun X : Cantor => X ∈ inputEvent π v) (nextSupport π v : Set ℕ) := + (π.dependsOn_inputEvent v).mono (by intro q hq; exact Finset.mem_insert_of_mem hq) + +private theorem child_dependsOn_nextSupport (π : ScanRule) (v : List Bool) (b : Bool) : + DependsOn (fun X : Cantor => X ∈ inputEvent π (v ++ [b])) (nextSupport π v : Set ℕ) := by + simpa only [nextSupport, π.queriedPositions_snoc] using π.dependsOn_inputEvent (v ++ [b]) + +theorem parent_mass_eq_stage (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) + (π : ScanRule) (v : List Bool) (n : ℕ) (hn : BlockProduct.cutoff B (nextSupport π v) ≤ n) : + BlockProduct.law B hdis (inputEvent π v) = PrefixStage.law B n (inputEvent π v) := + BlockProduct.law_apply_eq_stage B hdis (nextSupport π v) (inputEvent π v) + (parent_dependsOn_nextSupport π v) n hn + +theorem child_mass_eq_stage (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) + (π : ScanRule) (v : List Bool) (b : Bool) + (n : ℕ) (hn : BlockProduct.cutoff B (nextSupport π v) ≤ n) : + BlockProduct.law B hdis (inputEvent π (v ++ [b])) = + PrefixStage.law B n (inputEvent π (v ++ [b])) := + BlockProduct.law_apply_eq_stage B hdis (nextSupport π v) (inputEvent π (v ++ [b])) + (child_dependsOn_nextSupport π v b) n hn + +/-- Under the actual infinite law, a block query with no rank drop splits its +transcript mass equally between its two children. Null histories are included. -/ +theorem child_mass_of_no_rank_drop_in_block (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) + (k : ℕ) (π : ScanRule) (v : List Bool) (hq : π.query v ∈ (B k).support) + (hnodrop : ¬(B k).remainingRank π (v ++ [false]) < (B k).remainingRank π v) (b : Bool) : + BlockProduct.law B hdis (inputEvent π (v ++ [b])) = + (1 / 2 : ℝ≥0∞) * BlockProduct.law B hdis (inputEvent π v) := by + let n := max (BlockProduct.cutoff B (nextSupport π v)) (k + 1) + rw [child_mass_eq_stage B hdis π v b n (Nat.le_max_left _ _), + parent_mass_eq_stage B hdis π v n (Nat.le_max_left _ _)] + exact prefix_child_mass_of_no_rank_drop B hdis n k + (lt_of_lt_of_le (Nat.lt_succ_self k) (Nat.le_max_right _ _)) π v hq hnodrop b + +/-- A query outside all blocks is fair under the infinite law, including null histories. -/ +theorem child_mass_of_free (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) + (π : ScanRule) (v : List Bool) (hfree : ∀ k, π.query v ∉ (B k).support) (b : Bool) : + BlockProduct.law B hdis (inputEvent π (v ++ [b])) = + (1 / 2 : ℝ≥0∞) * BlockProduct.law B hdis (inputEvent π v) := by + let n := max (BlockProduct.cutoff B (nextSupport π v)) 1 + rw [child_mass_eq_stage B hdis π v b n (Nat.le_max_left _ _), + parent_mass_eq_stage B hdis π v n (Nat.le_max_left _ _)] + exact prefix_child_mass_of_free B hdis n + (lt_of_lt_of_le (by omega : 0 < 1) (Nat.le_max_right _ _)) π v hfree b + +/-- Every non-forced query obeys the exact fair child-mass identity for the constructed +infinite block law. This is the input required by the fair/forced capital argument. -/ +theorem child_mass_of_not_forced (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) + (π : ScanRule) (v : List Bool) (hnot : ¬forced B π v) (b : Bool) : + BlockProduct.law B hdis (inputEvent π (v ++ [b])) = + (1 / 2 : ℝ≥0∞) * BlockProduct.law B hdis (inputEvent π v) := by + classical + by_cases hmem : ∃ k, π.query v ∈ (B k).support + · obtain ⟨k, hk⟩ := hmem + apply child_mass_of_no_rank_drop_in_block B hdis k π v hk _ b + intro hdrop + exact hnot ⟨k, hk, hdrop⟩ + · exact child_mass_of_free B hdis π v (fun k hk => hmem ⟨k, hk⟩) b + +/-- A forced query gives all parent mass to one child and zero mass to the other under +the actual infinite block law. The statement also includes null parent events. -/ +theorem child_mass_forced (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) + (π : ScanRule) (v : List Bool) (hforce : forced B π v) : + ∃ b : Bool, BlockProduct.law B hdis (inputEvent π (v ++ [b])) = + BlockProduct.law B hdis (inputEvent π v) ∧ + BlockProduct.law B hdis (inputEvent π (v ++ [!b])) = 0 := by + obtain ⟨k, hq, hdrop⟩ := hforce + let n := max (BlockProduct.cutoff B (nextSupport π v)) (k + 1) + obtain ⟨b, hb, hnb⟩ := prefix_child_mass_forced B hdis n k + (lt_of_lt_of_le (Nat.lt_succ_self k) (Nat.le_max_right _ _)) π v hq hdrop + refine ⟨b, ?_, ?_⟩ + · rw [child_mass_eq_stage B hdis π v b n (Nat.le_max_left _ _), + parent_mass_eq_stage B hdis π v n (Nat.le_max_left _ _)] + exact hb + · rw [child_mass_eq_stage B hdis π v (!b) n (Nat.le_max_left _ _)] + exact hnb + +/-- The equivalent convenient hypothesis that no block loses rank at this query. -/ +theorem child_mass_of_no_rank_drop (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) + (π : ScanRule) (v : List Bool) + (hnodrop : ∀ k, ¬(B k).remainingRank π (v ++ [false]) < (B k).remainingRank π v) + (b : Bool) : + BlockProduct.law B hdis (inputEvent π (v ++ [b])) = + (1 / 2 : ℝ≥0∞) * BlockProduct.law B hdis (inputEvent π v) := + child_mass_of_not_forced B hdis π v (fun ⟨k, _, hk⟩ => hnodrop k hk) b + +/-- For a positive-probability transcript, a non-forced next answer is conditionally fair +under the constructed infinite law. -/ +theorem cond_next_bit_eq_half (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) + (π : ScanRule) (v : List Bool) (hnot : ¬forced B π v) + (hpos : BlockProduct.law B hdis (inputEvent π v) ≠ 0) (b : Bool) : + (cond (BlockProduct.law B hdis) (inputEvent π v)) (bitEvent (π.query v) b) = + (1 / 2 : ℝ≥0∞) := by + rw [cond_apply (measurableSet_inputEvent π v), ← inputEvent_snoc, + child_mass_of_not_forced B hdis π v hnot b, mul_left_comm, + ENNReal.inv_mul_cancel hpos (measure_ne_top _ _), mul_one] + +/-- For a positive-probability transcript, a forced query has a deterministic conditional +answer under the constructed infinite law. -/ +theorem cond_next_bit_forced (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) + (π : ScanRule) (v : List Bool) (hforce : forced B π v) + (hpos : BlockProduct.law B hdis (inputEvent π v) ≠ 0) : + ∃ b : Bool, + (cond (BlockProduct.law B hdis) (inputEvent π v)) (bitEvent (π.query v) b) = 1 ∧ + (cond (BlockProduct.law B hdis) (inputEvent π v)) (bitEvent (π.query v) (!b)) = 0 := by + obtain ⟨b, hb, hnb⟩ := child_mass_forced B hdis π v hforce + refine ⟨b, ?_, ?_⟩ + · rw [cond_apply (measurableSet_inputEvent π v), ← inputEvent_snoc, hb, + ENNReal.inv_mul_cancel hpos (measure_ne_top _ _)] + · rw [cond_apply (measurableSet_inputEvent π v), ← inputEvent_snoc, hnb, mul_zero] + +end Klr.BlockProductAnswer diff --git a/LeanPool/KLRandomness/BlockRandomness.lean b/LeanPool/KLRandomness/BlockRandomness.lean new file mode 100644 index 0000000000..a6763b10d9 --- /dev/null +++ b/LeanPool/KLRandomness/BlockRandomness.lean @@ -0,0 +1,139 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.BlockProductAnswer +public import LeanPool.KLRandomness.FairForced +public import LeanPool.KLRandomness.StrategyCountability +public import LeanPool.KLRandomness.MartinLof +public import LeanPool.KLRandomness.DescriptionBudget +public import LeanPool.KLRandomness.EarlyLateWagers + +/-! +# The probabilistic reduction for the separating construction + +For an actual disjoint affine-block law, no-drop queries have fair child +probabilities. Thus almost-sure summability of the absolute wagers on rank-drop +queries makes each normalized strategy fail almost surely. Countability and +success-preserving normalization then give almost-sure KL randomness. + +The final conditional existence theorem leaves the construction's two output +obligations explicit: the forced-wager estimates and coverage of all block +solutions by one genuine Martin-Löf test. It does not assert that suitable +blocks or descriptions have already been constructed. +-/ + +@[expose] public section + +namespace Klr.BlockRandomness + +open MeasureTheory +open scoped ENNReal + +/-- Select exactly those histories at which the next query causes no block rank drop. -/ +noncomputable def fairSelect (B : ℕ → AffineBlock) (π : ScanRule) : List Bool → Bool := by + classical + exact fun v => decide (¬BlockProductAnswer.forced B π v) + +/-- The absolute wager series restricted to actual rank-drop queries. -/ +noncomputable def forcedWagers (B : ℕ → AffineBlock) (s : BettingStrategy) + (X : Cantor) (n : ℕ) : ℝ := by + classical + exact if BlockProductAnswer.forced B s.scan (s.scan.transcript X n) + then |s.capital.wager (s.scan.transcript X n)| else 0 + +theorem forcedAmount_eq (B : ℕ → AffineBlock) (s : BettingStrategy) (X : Cantor) (n : ℕ) : + FairForced.forcedAmount (fairSelect B s.scan) s.capital.wager (s.scan.transcript X n) = + forcedWagers B s X n := by + classical + by_cases h : BlockProductAnswer.forced B s.scan (s.scan.transcript X n) <;> + simp [FairForced.forcedAmount, fairSelect, forcedWagers, h] + +/-- The actual infinite block law satisfies the fair-step hypothesis of the capital theorem. -/ +theorem fairLaw (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) (π : ScanRule) : + FairForced.FairLaw (BlockProduct.law B hdis) π (fairSelect B π) := by + intro v hv b + have hnot : ¬BlockProductAnswer.forced B π v := by + simpa only [fairSelect, decide_eq_true_eq] using hv + exact BlockProductAnswer.child_mass_of_not_forced B hdis π v hnot b + +/-- A bounded-wager strategy fails under the actual block law if its rank-drop wagers sum. -/ +theorem ae_not_succeeds (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) + (s : BettingStrategy) (hw : ∀ v, |s.capital.wager v| ≤ (1 / 2 : ℝ)) + (hforced : ∀ᵐ X ∂BlockProduct.law B hdis, Summable (forcedWagers B s X)) : + ∀ᵐ X ∂BlockProduct.law B hdis, ¬s.Succeeds X := by + apply s.ae_not_succeeds_of_fair_forced (BlockProduct.law B hdis) (fairSelect B s.scan) + hw (fairLaw B hdis s.scan) + simpa only [forcedAmount_eq] using hforced + +/-- The concrete remaining probabilistic obligation for almost-sure KL randomness. -/ +theorem ae_kolmogorovLovelandRandom_of_forced_summable (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) + (hforced : ∀ s : BettingStrategy, ∀ᵐ X ∂BlockProduct.law B hdis, + Summable (forcedWagers B s.normalize X)) : + ∀ᵐ X ∂BlockProduct.law B hdis, KolmogorovLovelandRandom X := by + apply ae_kolmogorovLovelandRandom_of_normalized + intro s + exact ae_not_succeeds B hdis s.normalize s.normalize_wager_abs_le_half (hforced s) + +/-- Actual late-drop probabilities and early-wager expectations supply forced summability. -/ +theorem ae_kolmogorovLovelandRandom_of_early_late (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) (V : ℕ → ℕ) + (hlate : ∀ s : BettingStrategy, + (∑' j, BlockProduct.law B hdis (DropEvents.lateEvent B s.normalize.scan V j)) < ∞) + (hearly : ∀ s : BettingStrategy, + (∑' j, ∫⁻ X, ENNReal.ofReal + (EarlyLateWagers.earlyWager B s.normalize.scan s.normalize.capital.wager V j X) + ∂BlockProduct.law B hdis) < ∞) : + ∀ᵐ X ∂BlockProduct.law B hdis, KolmogorovLovelandRandom X := by + apply ae_kolmogorovLovelandRandom_of_forced_summable B hdis + intro s + exact EarlyLateWagers.ae_summable_forcedWager (BlockProduct.law B hdis) B + s.normalize.scan s.normalize.capital.wager V (hlate s) (hearly s) + +/-- Conditional final reduction: forced-wager control and a genuine test covering every +block solution produce a separating sequence. Constructing such blocks remains necessary. -/ +theorem exists_separating_of_test_cover (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) + (hforced : ∀ s : BettingStrategy, ∀ᵐ X ∂BlockProduct.law B hdis, + Summable (forcedWagers B s.normalize X)) + (T : MartinLofTest) + (hcover : ∀ X : Cantor, (∀ k, X ∈ (B k).event) → T.Fails X) : + ∃ X : Cantor, KolmogorovLovelandRandom X ∧ ¬MartinLofRandom X := by + have hboth : ∀ᵐ X ∂BlockProduct.law B hdis, + KolmogorovLovelandRandom X ∧ ¬MartinLofRandom X := by + filter_upwards [ae_kolmogorovLovelandRandom_of_forced_summable B hdis hforced, + BlockProduct.ae_all_blocks B hdis] with X hX hblocks + exact ⟨hX, fun hML => hML T (hcover X hblocks)⟩ + exact hboth.exists + +/-- The same reduction with the explicit uniform description-budget interface. At each +test level, one imposed block is covered by an event decoded from a sufficiently small +description. The actual decoder and stage descriptions remain construction obligations. -/ +theorem exists_separating_of_description_cover (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) + (hforced : ∀ s : BettingStrategy, ∀ᵐ X ∂BlockProduct.law B hdis, + Summable (forcedWagers B s.normalize X)) + {W : ℕ × List Bool × List Bool → Prop} (hW : REPred W) + (hbound : ∀ (n : ℕ) (p : List Bool), + fairCoin (cylinderUnion (fun v => W (n, p, v))) ≤ + (1 / 2 : ℝ≥0∞) ^ (2 * p.length + n + 1)) + (hcover : ∀ n : ℕ, ∃ (j : ℕ) (p : List Bool), + (B j).event ⊆ cylinderUnion (fun v => W (n, p, v))) : + ∃ X : Cantor, KolmogorovLovelandRandom X ∧ ¬MartinLofRandom X := by + obtain ⟨T, hT⟩ := exists_martinLofTest_of_description_family hW hbound + apply exists_separating_of_test_cover B hdis hforced T + intro X hX n + rw [hT n] + obtain ⟨j, p, hp⟩ := hcover n + exact Set.mem_iUnion.mpr ⟨p, hp (hX j)⟩ + +end Klr.BlockRandomness diff --git a/LeanPool/KLRandomness/Cantor.lean b/LeanPool/KLRandomness/Cantor.lean new file mode 100644 index 0000000000..b2d76b35a7 --- /dev/null +++ b/LeanPool/KLRandomness/Cantor.lean @@ -0,0 +1,93 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import Mathlib.Probability.Distributions.Bernoulli +public import Mathlib.Probability.ProductMeasure +public import Mathlib.MeasureTheory.Constructions.BorelSpace.Basic +import Mathlib.Tactic.NormNum + +/-! +# Cantor space and fair-coin measure + +Finite binary strings use `List Bool`; infinite binary sequences use `ℕ → Bool`. +The measure below is the actual infinite product of fair two-point measures. +-/ + +@[expose] public section + +namespace Klr + +open MeasureTheory +open scoped ENNReal NNReal + +/-- Cantor space, with the product topology and product measurable space. -/ +abbrev Cantor := ℕ → Bool + +/-- The cylinder consisting of the infinite extensions of a finite binary string. -/ +def cylinder (s : List Bool) : Set Cantor := + {X | ∀ i < s.length, X i = s.getD i false} + +@[simp] theorem mem_cylinder {s : List Bool} {X : Cantor} : + X ∈ cylinder s ↔ ∀ i < s.length, X i = s.getD i false := Iff.rfl + +@[simp] theorem cylinder_nil : cylinder [] = Set.univ := by + ext X + simp [cylinder] + +theorem cylinder_eq_pi (s : List Bool) : + cylinder s = Set.pi (Finset.range s.length) (fun i => {s.getD i false}) := by + ext X + simp [cylinder, Set.pi] + +theorem isOpen_cylinder (s : List Bool) : IsOpen (cylinder s) := by + rw [cylinder_eq_pi] + exact isOpen_set_pi (Finset.finite_toSet _) (fun _ _ => isOpen_discrete _) + +theorem isClosed_cylinder (s : List Bool) : IsClosed (cylinder s) := by + rw [cylinder_eq_pi] + exact isClosed_set_pi (fun _ _ => isClosed_singleton) + +theorem measurableSet_cylinder (s : List Bool) : MeasurableSet (cylinder s) := by + rw [cylinder_eq_pi] + exact MeasurableSet.pi (Finset.countable_toSet _) (fun _ _ => measurableSet_singleton _) + +/-- The fair probability measure on one bit. -/ +noncomputable def fairBit : Measure Bool := + ProbabilityTheory.bernoulliMeasure true false ⟨1 / 2, by norm_num, by norm_num⟩ + +instance : IsProbabilityMeasure fairBit := by + unfold fairBit + infer_instance + +@[simp] theorem fairBit_singleton (b : Bool) : fairBit {b} = (1 / 2 : ℝ≥0∞) := by + cases b <;> + norm_num [fairBit, ProbabilityTheory.bernoulliMeasure_apply, + unitInterval.toNNReal, unitInterval.symm] + all_goals + change ((1 / 2 : ℝ≥0) : ℝ≥0∞) = (2 : ℝ≥0∞)⁻¹ + norm_num + +/-- Independent fair coin tosses on all natural-number positions. -/ +noncomputable def fairCoin : Measure Cantor := + Measure.infinitePi (fun _ : ℕ => fairBit) + +instance : IsProbabilityMeasure fairCoin := by + unfold fairCoin + infer_instance + +/-- A finite specification of `|s|` bits has fair-coin measure `2⁻|s|`. -/ +@[simp] theorem fairCoin_cylinder (s : List Bool) : + fairCoin (cylinder s) = (1 / 2 : ℝ≥0∞) ^ s.length := by + rw [cylinder_eq_pi, fairCoin, Measure.infinitePi_pi] + · simp + · intro i hi + exact measurableSet_singleton _ + +end Klr diff --git a/LeanPool/KLRandomness/ComputableNonrandom.lean b/LeanPool/KLRandomness/ComputableNonrandom.lean new file mode 100644 index 0000000000..46af94a74e --- /dev/null +++ b/LeanPool/KLRandomness/ComputableNonrandom.lean @@ -0,0 +1,83 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.Betting +public import LeanPool.KLRandomness.MartinLof + +/-! +# Computable sequences fail Martin-Löf randomness + +The test at level `n` is the single cylinder determined by the first `n` bits +of the sequence. Its uniform effectiveness is proved from actual computability +of the sequence, and its measure is exactly `(1/2)^n`. +-/ + +@[expose] public section + +namespace Klr + +open MeasureTheory +open scoped ENNReal + +namespace ScanRule + +@[simp] theorem length_inputPrefix (X : Cantor) (n : ℕ) : + (inputPrefix X n).length = n := by + simp [inputPrefix] + +theorem getD_inputPrefix (X : Cantor) {n i : ℕ} (hi : i < n) : + (inputPrefix X n).getD i false = X i := by + simp [inputPrefix, List.getD_eq_getElem?_getD, List.getElem?_range hi] + +theorem mem_cylinder_inputPrefix (X : Cantor) (n : ℕ) : + X ∈ cylinder (inputPrefix X n) := by + intro i hi + exact (getD_inputPrefix X (by simpa using hi)).symm + +/-- A computable binary sequence has a computable function of finite prefixes. -/ +theorem computable_inputPrefix {X : Cantor} (hX : Computable X) : + Computable (inputPrefix X) := by + have hstep : Computable₂ (fun (_ : ℕ) (p : ℕ × List Bool) => p.2 ++ [X p.1]) := + (Computable.list_concat.comp (Computable.snd.comp Computable.snd) + (hX.comp (Computable.fst.comp Computable.snd))).to₂ + apply (Computable.nat_rec Computable.id (Computable.const []) hstep).of_eq + intro n + induction n with + | zero => rfl + | succ n ih => + simpa [inputPrefix, List.range_succ] using congrArg (fun s => s ++ [X n]) ih + +end ScanRule + +/-- The single-cylinder test for a computable sequence is uniformly effectively open. -/ +theorem computable_prefix_uniform {X : Cantor} (hX : Computable X) : + IsUniformlyEffectivelyOpen (fun n => cylinder (ScanRule.inputPrefix X n)) := by + have hp : ComputablePred (fun p : ℕ × List Bool => p.2 = ScanRule.inputPrefix X p.1) := + Computable.computablePred <| + Primrec.eq.computablePred.decide.comp <| + Computable.snd.pair ((ScanRule.computable_inputPrefix hX).comp Computable.fst) + refine ⟨fun p => p.2 = ScanRule.inputPrefix X p.1, hp.to_re, fun n => ?_⟩ + ext Y + simp [cylinderUnion] + +/-- No computable binary sequence is Martin-Löf random. -/ +theorem not_martinLofRandom_of_computable {X : Cantor} (hX : Computable X) : + ¬MartinLofRandom X := by + apply not_martinLofRandom_of_uniform (computable_prefix_uniform hX) + · intro n + simp + · exact ScanRule.mem_cylinder_inputPrefix X + +/-- In particular, Martin-Löf randomness implies incomputability. -/ +theorem MartinLofRandom.not_computable {X : Cantor} (hX : MartinLofRandom X) : + ¬Computable X := + fun h => not_martinLofRandom_of_computable h hX + +end Klr diff --git a/LeanPool/KLRandomness/ComputableRational.lean b/LeanPool/KLRandomness/ComputableRational.lean new file mode 100644 index 0000000000..bf0fb8969e --- /dev/null +++ b/LeanPool/KLRandomness/ComputableRational.lean @@ -0,0 +1,387 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.Betting +public import Mathlib.Computability.RE +public import Mathlib.Data.Rat.Lemmas +public import Mathlib.Data.Nat.Find +import Mathlib.Tactic.Ring + +/-! +# Computable rational arithmetic + +This file supplies explicit computability proofs for the canonical numerator and +denominator representation used by `ComputableRealCapital`. +-/ + +@[expose] public section + +namespace Klr.RationalComputability + +theorem primrec_int_split : Primrec Equiv.intEquivNatSumNat := by + apply Primrec.encode_iff.mp + exact Primrec.encode.of_eq (fun z => by cases z <;> rfl) + +theorem primrec_int_merge : Primrec Equiv.intEquivNatSumNat.symm := by + apply Primrec.encode_iff.mp + exact Primrec.encode.of_eq (fun z => by cases z <;> rfl) + +theorem primrec_int_ofNat : Primrec Int.ofNat := + primrec_int_merge.comp Primrec.sumInl + +theorem primrec_int_negSucc : Primrec Int.negSucc := + primrec_int_merge.comp Primrec.sumInr + +/-- The nonnegative part of an integer as a natural number. -/ +def positivePart : ℤ → ℕ + | .ofNat n => n + | .negSucc _ => 0 + +/-- The magnitude of the negative part of an integer. -/ +def negativePart : ℤ → ℕ + | .ofNat _ => 0 + | .negSucc n => n + 1 + +theorem primrec_positivePart : Primrec positivePart := + (Primrec.sumCasesOn primrec_int_split Primrec.snd.to₂ (Primrec.const 0).to₂).of_eq + (fun z => by cases z <;> rfl) + +theorem primrec_negativePart : Primrec negativePart := + (Primrec.sumCasesOn primrec_int_split (Primrec.const 0).to₂ + (Primrec.succ.comp Primrec.snd).to₂).of_eq (fun z => by cases z <;> rfl) + +theorem int_eq_parts (z : ℤ) : z = (positivePart z : ℤ) - negativePart z := by + cases z <;> simp [positivePart, negativePart, Int.negSucc_eq] + +theorem primrec_int_natAbs : Primrec Int.natAbs := + (Primrec.nat_add.comp primrec_positivePart primrec_negativePart).of_eq + (fun z => by cases z <;> simp [positivePart, negativePart]) + +/-- Integer difference of two natural numbers without truncation. -/ +def signedDifference (a b : ℕ) : ℤ := + if b ≤ a then .ofNat (a - b) else .negSucc (b - a - 1) + +theorem signedDifference_eq (a b : ℕ) : signedDifference a b = (a : ℤ) - b := by + unfold signedDifference + split_ifs with h + · change ((a - b : ℕ) : ℤ) = _ + exact Int.ofNat_sub h + · rw [Int.negSucc_eq] + omega + +theorem primrec_signedDifference : Primrec₂ signedDifference := + (Primrec.ite (Primrec.nat_le.comp Primrec.snd Primrec.fst) + (primrec_int_ofNat.comp (Primrec.nat_sub.comp Primrec.fst Primrec.snd)) + (primrec_int_negSucc.comp (Primrec.nat_sub.comp + (Primrec.nat_sub.comp Primrec.snd Primrec.fst) (Primrec.const 1)))).to₂ + +theorem primrec_int_neg : Primrec (fun z : ℤ => -z) := + (primrec_signedDifference.comp primrec_negativePart primrec_positivePart).of_eq + (fun z => by rw [signedDifference_eq]; have h := int_eq_parts z; omega) + +theorem primrec_int_add : Primrec₂ (fun a b : ℤ => a + b) := by + apply (primrec_signedDifference.comp + (Primrec.nat_add.comp (primrec_positivePart.comp Primrec.fst) + (primrec_positivePart.comp Primrec.snd)) + (Primrec.nat_add.comp (primrec_negativePart.comp Primrec.fst) + (primrec_negativePart.comp Primrec.snd))).to₂.of_eq + intro a b + rw [signedDifference_eq] + conv_rhs => rw [int_eq_parts a, int_eq_parts b] + push_cast + ring + +theorem primrec_int_mul : Primrec₂ (fun a b : ℤ => a * b) := by + apply (primrec_signedDifference.comp + (Primrec.nat_add.comp + (Primrec.nat_mul.comp (primrec_positivePart.comp Primrec.fst) + (primrec_positivePart.comp Primrec.snd)) + (Primrec.nat_mul.comp (primrec_negativePart.comp Primrec.fst) + (primrec_negativePart.comp Primrec.snd))) + (Primrec.nat_add.comp + (Primrec.nat_mul.comp (primrec_positivePart.comp Primrec.fst) + (primrec_negativePart.comp Primrec.snd)) + (Primrec.nat_mul.comp (primrec_negativePart.comp Primrec.fst) + (primrec_positivePart.comp Primrec.snd)))).to₂.of_eq + intro a b + rw [signedDifference_eq] + conv_rhs => rw [int_eq_parts a, int_eq_parts b] + push_cast + ring + +theorem primrec_int_le : PrimrecRel (fun a b : ℤ => a ≤ b) := by + apply (Primrec.nat_le.comp + (Primrec.nat_add.comp (primrec_positivePart.comp Primrec.fst) + (primrec_negativePart.comp Primrec.snd)) + (Primrec.nat_add.comp (primrec_positivePart.comp Primrec.snd) + (primrec_negativePart.comp Primrec.fst))).of_eq + intro p + have ha := int_eq_parts p.1 + have hb := int_eq_parts p.2 + omega + +theorem gcd_eq_findGreatest (a b : ℕ) : + Nat.findGreatest (fun d => a % d = 0 ∧ b % d = 0) (a + b) = a.gcd b := by + rw [Nat.findGreatest_eq_iff] + refine ⟨?_, fun _ => ⟨Nat.mod_eq_zero_of_dvd (Nat.gcd_dvd_left a b), + Nat.mod_eq_zero_of_dvd (Nat.gcd_dvd_right a b)⟩, ?_⟩ + · by_cases ha : a = 0 + · simp [ha] + · exact (Nat.gcd_le_left b (Nat.pos_of_ne_zero ha)).trans (Nat.le_add_right a b) + · intro n hn hbound hdiv + have hd : n ∣ a.gcd b := + Nat.dvd_gcd (Nat.dvd_of_mod_eq_zero hdiv.1) (Nat.dvd_of_mod_eq_zero hdiv.2) + by_cases hg : a.gcd b = 0 + · obtain ⟨ha, hb⟩ := Nat.gcd_eq_zero_iff.mp hg + omega + · exact (not_le_of_gt hn) (Nat.le_of_dvd (Nat.pos_of_ne_zero hg) hd) + +theorem primrec_nat_gcd : Primrec₂ Nat.gcd := by + apply (Primrec.nat_findGreatest + (p := fun (ab : ℕ × ℕ) d => ab.1 % d = 0 ∧ ab.2 % d = 0) Primrec.nat_add + ((Primrec.eq.comp (Primrec.nat_mod.comp (Primrec.fst.comp Primrec.fst) Primrec.snd) + (Primrec.const 0)).and + (Primrec.eq.comp (Primrec.nat_mod.comp (Primrec.snd.comp Primrec.fst) Primrec.snd) + (Primrec.const 0)))).to₂.of_eq + exact gcd_eq_findGreatest + +/-- A numerator and positive denominator in lowest terms. -/ +def IsCanonical (p : ℤ × ℕ) : Prop := p.2 ≠ 0 ∧ p.1.natAbs.Coprime p.2 + +instance : DecidablePred IsCanonical := fun _ => inferInstanceAs (Decidable (_ ∧ _)) + +theorem primrec_isCanonical : PrimrecPred IsCanonical := + (Primrec.eq.comp Primrec.snd (Primrec.const 0)).not.and + (Primrec.eq.comp + (primrec_nat_gcd.comp (primrec_int_natAbs.comp Primrec.fst) Primrec.snd) + (Primrec.const 1)) + +/-- Canonical signed numerator and positive denominator codes. -/ +abbrev RationalCode := {p : ℤ × ℕ // IsCanonical p} + +instance : Primcodable RationalCode := Primcodable.subtype primrec_isCanonical + +/-- The bijection between rationals and reduced numerator-denominator pairs. -/ +def ratCodeEquiv : ℚ ≃ RationalCode where + toFun q := ⟨(q.num, q.den), q.den_nz, q.reduced⟩ + invFun p := ⟨p.val.1, p.val.2, p.property.1, p.property.2⟩ + left_inv q := by cases q; rfl + right_inv p := by rcases p with ⟨⟨n, d⟩, h⟩; rfl + +/-- A primitive-recursive presentation of the rationals by their canonical fields. -/ +instance instPrimcodableRational : Primcodable ℚ := Primcodable.ofEquiv RationalCode ratCodeEquiv + +theorem primrec_rat_numDen : Primrec (fun q : ℚ => (q.num, q.den)) := + (Primrec.subtype_val (hp := primrec_isCanonical)).comp (Primrec.of_equiv + (e := ratCodeEquiv)) + +theorem primrec_rat_num : Primrec Rat.num := Primrec.fst.comp primrec_rat_numDen + +theorem primrec_rat_den : Primrec Rat.den := Primrec.snd.comp primrec_rat_numDen + +theorem primrec_rat_of_numDen {α : Type*} [Primcodable α] {f : α → ℚ} + (hf : Primrec (fun a => ((f a).num, (f a).den))) : Primrec f := by + have hcode : Primrec (fun a => ratCodeEquiv (f a)) := + Primrec.subtype_mk (hp := primrec_isCanonical) hf + exact (Primrec.of_equiv_iff ratCodeEquiv).mp hcode + +theorem computable_rat_of_numDen {α : Type*} [Primcodable α] {f : α → ℚ} + (hf : Computable (fun a => ((f a).num, (f a).den))) : Computable f := by + have hcode : Computable (fun a => ratCodeEquiv (f a)) := + Computable.subtype_mk primrec_isCanonical hf + have hc : Computable (fun a => ratCodeEquiv.symm (ratCodeEquiv (f a))) := + (Primrec.of_equiv_symm (e := ratCodeEquiv)).to_comp.comp hcode + exact hc.of_eq (fun a => ratCodeEquiv.symm_apply_apply (f a)) + +/-- Divide an integer magnitude by a natural number and retain its sign. -/ +def signedQuotient (n : ℤ) (d : ℕ) : ℤ := + signedDifference (positivePart n / d) (negativePart n / d) + +theorem primrec_signedQuotient : Primrec₂ signedQuotient := + (primrec_signedDifference.comp + (Primrec.nat_div.comp (primrec_positivePart.comp Primrec.fst) Primrec.snd) + (Primrec.nat_div.comp (primrec_negativePart.comp Primrec.fst) Primrec.snd)).to₂ + +theorem signedQuotient_eq_of_dvd (n : ℤ) (d : ℕ) (hd : (d : ℤ) ∣ n) : + signedQuotient n d = n / d := by + cases n with + | ofNat n => + simp [signedQuotient, positivePart, negativePart, signedDifference_eq, + Int.natCast_ediv] + | negSucc n => + have hd' : (d : ℤ) ∣ ((n + 1 : ℕ) : ℤ) := by + simpa [Int.negSucc_eq] using (dvd_neg.mp hd) + simp only [signedQuotient, positivePart, negativePart, signedDifference_eq, + Nat.zero_div, Nat.cast_zero, zero_sub] + rw [Int.negSucc_eq, show (n : ℤ) + 1 = ((n + 1 : ℕ) : ℤ) by simp, + Int.neg_ediv_of_dvd hd', Int.natCast_ediv] + +/-- Reduce a numerator-denominator pair, sending a zero denominator to the code for zero. -/ +def normalizeCode (p : ℤ × ℕ) : ℤ × ℕ := + if p.2 = 0 then (0, 1) + else (signedQuotient p.1 (p.2.gcd p.1.natAbs), p.2 / p.2.gcd p.1.natAbs) + +theorem primrec_normalizeCode : Primrec normalizeCode := + Primrec.ite (Primrec.eq.comp Primrec.snd (Primrec.const 0)) (Primrec.const (0, 1)) + ((primrec_signedQuotient.comp Primrec.fst + (primrec_nat_gcd.comp Primrec.snd (primrec_int_natAbs.comp Primrec.fst))).pair + (Primrec.nat_div.comp Primrec.snd + (primrec_nat_gcd.comp Primrec.snd (primrec_int_natAbs.comp Primrec.fst)))) + +theorem normalizeCode_eq (p : ℤ × ℕ) : + normalizeCode p = ((mkRat p.1 p.2).num, (mkRat p.1 p.2).den) := by + by_cases hd : p.2 = 0 + · simp [normalizeCode, hd] + · simp only [normalizeCode, hd, ite_false, Rat.num_mkRat, Rat.den_mkRat] + congr 1 + exact signedQuotient_eq_of_dvd _ _ + (Int.ofNat_dvd_left.mpr (Nat.gcd_dvd_right p.2 p.1.natAbs)) + +theorem primrec_mkRat : Primrec₂ mkRat := by + apply primrec_rat_of_numDen + exact primrec_normalizeCode.of_eq normalizeCode_eq + +theorem primrec_rat_intCast : Primrec (fun n : ℤ => (n : ℚ)) := + (primrec_mkRat.comp Primrec.id (Primrec.const 1)).of_eq (fun n => by + simp [Rat.mkRat_eq_divInt]) + +theorem primrec_rat_natCast : Primrec (fun n : ℕ => (n : ℚ)) := + primrec_rat_intCast.comp primrec_int_ofNat + +theorem primrec_rat_neg : Primrec (fun q : ℚ => -q) := by + apply primrec_rat_of_numDen + exact ((primrec_int_neg.comp primrec_rat_num).pair primrec_rat_den).of_eq + (fun q => by simp) + +theorem primrec_rat_add : Primrec₂ (fun a b : ℚ => a + b) := by + apply (primrec_mkRat.comp + (primrec_int_add.comp + (primrec_int_mul.comp (primrec_rat_num.comp Primrec.fst) + (primrec_int_ofNat.comp (primrec_rat_den.comp Primrec.snd))) + (primrec_int_mul.comp (primrec_rat_num.comp Primrec.snd) + (primrec_int_ofNat.comp (primrec_rat_den.comp Primrec.fst)))) + (Primrec.nat_mul.comp (primrec_rat_den.comp Primrec.fst) + (primrec_rat_den.comp Primrec.snd))).to₂.of_eq + intro a b + rw [Rat.add_def, Rat.normalize_eq_mkRat] + rfl + +theorem primrec_rat_mul : Primrec₂ (fun a b : ℚ => a * b) := by + apply (primrec_mkRat.comp + (primrec_int_mul.comp (primrec_rat_num.comp Primrec.fst) + (primrec_rat_num.comp Primrec.snd)) + (Primrec.nat_mul.comp (primrec_rat_den.comp Primrec.fst) + (primrec_rat_den.comp Primrec.snd))).to₂.of_eq + intro a b + rw [Rat.mul_def, Rat.normalize_eq_mkRat] + +theorem primrec_rat_divInt : Primrec₂ Rat.divInt := by + apply (Primrec.sumCasesOn (primrec_int_split.comp Primrec.snd) + (primrec_mkRat.comp (Primrec.fst.comp Primrec.fst) Primrec.snd).to₂ + (primrec_mkRat.comp (primrec_int_neg.comp (Primrec.fst.comp Primrec.fst)) + (Primrec.succ.comp Primrec.snd)).to₂).to₂.of_eq + intro n d + cases d <;> rfl + +theorem primrec_rat_inv : Primrec (fun q : ℚ => q⁻¹) := + (primrec_rat_divInt.comp (primrec_int_ofNat.comp primrec_rat_den) primrec_rat_num).of_eq + (fun q => (Rat.inv_def q).symm) + +theorem primrec_rat_div : Primrec₂ (fun a b : ℚ => a / b) := + (primrec_rat_mul.comp Primrec.fst (primrec_rat_inv.comp Primrec.snd)).to₂.of_eq + (fun a b => (div_eq_mul_inv a b).symm) + +theorem primrec_rat_sub : Primrec₂ (fun a b : ℚ => a - b) := + (primrec_rat_add.comp Primrec.fst (primrec_rat_neg.comp Primrec.snd)).to₂.of_eq + (fun a b => (sub_eq_add_neg a b).symm) + +theorem primrec_rat_le : PrimrecRel (fun a b : ℚ => a ≤ b) := by + apply (primrec_int_le.comp + (primrec_int_mul.comp (primrec_rat_num.comp Primrec.fst) + (primrec_int_ofNat.comp (primrec_rat_den.comp Primrec.snd))) + (primrec_int_mul.comp (primrec_rat_num.comp Primrec.snd) + (primrec_int_ofNat.comp (primrec_rat_den.comp Primrec.fst)))).of_eq + intro p + exact (Rat.le_iff p.1 p.2).symm + +theorem primrec_rat_min : Primrec₂ (min : ℚ → ℚ → ℚ) := + (Primrec.ite primrec_rat_le Primrec.fst Primrec.snd).to₂.of_eq + (fun a b => (min_def a b).symm) + +theorem primrec_rat_max : Primrec₂ (max : ℚ → ℚ → ℚ) := + (Primrec.ite primrec_rat_le Primrec.snd Primrec.fst).to₂.of_eq + (fun a b => (max_def a b).symm) + +end Klr.RationalComputability + +namespace Klr + +/-- Rational computability expressed in the canonical fields used by real-capital witnesses. -/ +def ComputableRat {α : Type*} [Primcodable α] (f : α → ℚ) : Prop := + Computable (fun a => ((f a).num, (f a).den)) + +theorem computableRat_iff {α : Type*} [Primcodable α] {f : α → ℚ} : + ComputableRat f ↔ Computable f := + ⟨RationalComputability.computable_rat_of_numDen, + fun h => RationalComputability.primrec_rat_numDen.to_comp.comp h⟩ + +namespace ComputableRat + +variable {α β : Type*} [Primcodable α] [Primcodable β] {f g : α → ℚ} + +theorem const (q : ℚ) : ComputableRat (fun _ : α => q) := Computable.const _ + +theorem comp (hf : ComputableRat f) {g : β → α} (hg : Computable g) : + ComputableRat (fun b => f (g b)) := Computable.comp hf hg + +theorem add (hf : ComputableRat f) (hg : ComputableRat g) : + ComputableRat (fun a => f a + g a) := + computableRat_iff.mpr (RationalComputability.primrec_rat_add.to_comp.comp + (computableRat_iff.mp hf) (computableRat_iff.mp hg)) + +theorem mul (hf : ComputableRat f) (hg : ComputableRat g) : + ComputableRat (fun a => f a * g a) := + computableRat_iff.mpr (RationalComputability.primrec_rat_mul.to_comp.comp + (computableRat_iff.mp hf) (computableRat_iff.mp hg)) + +theorem neg (hf : ComputableRat f) : ComputableRat (fun a => -f a) := + computableRat_iff.mpr (RationalComputability.primrec_rat_neg.to_comp.comp + (computableRat_iff.mp hf)) + +theorem div (hf : ComputableRat f) (hg : ComputableRat g) : + ComputableRat (fun a => f a / g a) := + computableRat_iff.mpr (RationalComputability.primrec_rat_div.to_comp.comp + (computableRat_iff.mp hf) (computableRat_iff.mp hg)) + +theorem min (hf : ComputableRat f) (hg : ComputableRat g) : + ComputableRat (fun a => min (f a) (g a)) := + computableRat_iff.mpr (RationalComputability.primrec_rat_min.to_comp.comp + (computableRat_iff.mp hf) (computableRat_iff.mp hg)) + +theorem max (hf : ComputableRat f) (hg : ComputableRat g) : + ComputableRat (fun a => max (f a) (g a)) := + computableRat_iff.mpr (RationalComputability.primrec_rat_max.to_comp.comp + (computableRat_iff.mp hf) (computableRat_iff.mp hg)) + +end ComputableRat + +/-- Computable rational capital is a special case of the existing computable-real interface. -/ +theorem computableRealCapital_of_rat {d : List Bool → ℚ} (hd : Computable d) : + ComputableRealCapital (fun v => (d v : ℝ)) := by + refine ⟨fun v _ => d v, ?_, ?_⟩ + · exact RationalComputability.primrec_rat_numDen.to_comp.comp (hd.comp Computable.fst) + · intro v n + simp + +theorem computableRealCapital_of_computableRat {d : List Bool → ℚ} + (hd : ComputableRat d) : ComputableRealCapital (fun v => (d v : ℝ)) := + computableRealCapital_of_rat (computableRat_iff.mp hd) + +end Klr diff --git a/LeanPool/KLRandomness/ConfinedStageConstruction.lean b/LeanPool/KLRandomness/ConfinedStageConstruction.lean new file mode 100644 index 0000000000..d472213251 --- /dev/null +++ b/LeanPool/KLRandomness/ConfinedStageConstruction.lean @@ -0,0 +1,205 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.StageConstruction +public import LeanPool.KLRandomness.ConfinedStageRecursion +import Mathlib.Tactic.Linarith +import Mathlib.Tactic.Positivity + +/-! +# Stage construction with prescribed coordinate sets + +The finite-stage proof accepts a supplied family of good pools, retaining +an arbitrary coordinate predicate for each stage. Every analytic estimate +is the same as in the unrestricted construction. Support confinement is +retained before choosing the next history. +-/ + +@[expose] public section + +noncomputable section + +namespace Klr.ConfinedStageConstruction + +open Filter MeasureTheory StageChoice StagePreHorizon StagePrepared +open scoped BigOperators Topology + +/-- The only added input to the stage construction: good pools whose members +satisfy a prescribed coordinate predicate at each stage. -/ +def PoolSupply (s : ℕ → BettingStrategy) (H : ℕ → Set Cantor) + (A : ℕ → ℕ → Prop) : Prop := + ∀ (n : ℕ) (η : ℝ), 0 < η → ∀ z : ℕ, + ∃ τ : ℚ, 0 < τ ∧ τ < 1 / 4 ∧ + ∃ e : Nat.Partrec.Code, ∀ᶠ M : ℕ in atTop, + ∃ G : List ℕ, PoolAdvice.encodePool G ∈ e.eval M ∧ + PoolConstruction.GoodPool (fun i => (s i).normalize.scan) + H (n + 1) η z τ M G ∧ ∀ b ∈ G, A n b + +/-- Supplied confined pools give the same uniform candidate bounds. -/ +theorem eventual_candidates (s : ℕ → BettingStrategy) + (H : ℕ → Set Cantor) (hH : ∀ i, MeasurableSet (H i)) + (A : ℕ → ℕ → Prop) (hpool : PoolSupply s H A) : + ∀ (B : ℕ → AffineBlock), + Pairwise (fun i j => Disjoint (B i).support (B j).support) → + ∀ (n z : ℕ) (ε : ℝ), 0 < ε → + ∃ η : ℚ, 0 < η ∧ + ((n + 1 : ℕ) : ℝ) * (2 : ℝ) ^ (∑ k : Fin n, (B k).rank) * + ((η : ℝ) + η) < ε / 2 ∧ + ∃ τ : ℚ, 0 < τ ∧ τ < 1 / 4 ∧ + ∃ e : Nat.Partrec.Code, ∀ᶠ r : ℕ in atTop, + ∃ (G : List ℕ) (L : SparseListSearch.CodeList) + (hG : PoolConstruction.GoodPool (fun i => (s i).normalize.scan) + H (n + 1) (η : ℝ) z τ (SparseParameters.blockSize r) G) + (hL : L ∈ SparseListConstruction.construct τ η r), + PoolAdvice.encodePool G ∈ e.eval (SparseParameters.blockSize r) ∧ + (∀ b ∈ G, A n b) ∧ + ∃ q : Fin L.length, 0 < r ∧ q.val < r ^ 24 ∧ + (∀ a ≤ n, (∑ i : Fin (n + 1), + (PrefixStage.law B a).real (highMissInput (s i) (H i) G)) < ε) ∧ + ∀ y : Fin r → ZMod 2, + (∑ i : Fin (n + 1), wagerCost (PrefixStage.law B n) (s i) + (candidate hG.1 hG.2.1 hL q y)) < ε ∧ + ∀ a ≤ n, (∑ i : Fin (n + 1), (PrefixStage.law B a).real + (lowDropInput (s i) (H i) (candidate hG.1 hG.2.1 hL q y))) < ε := by + intro B hdis n z ε hε + let d : ℝ := (2 : ℝ) ^ (∑ k : Fin n, (B k).rank) + let c : ℝ := ((n + 1 : ℕ) : ℝ) * d + have hd : 0 < d := by dsimp [d]; positivity + have hc : 0 < c := by dsimp [c]; positivity + obtain ⟨η, hη0, hηsmall⟩ := exists_rat_btwn (show (0 : ℝ) < ε / (4 * c) by positivity) + have hη : (0 : ℚ) < η := by exact_mod_cast hη0 + have hsmall : c * (η : ℝ) < ε / 4 := by + have ht := (lt_div_iff₀ (show (0 : ℝ) < 4 * c by positivity)).mp hηsmall + nlinarith + have hbudget : c * ((η : ℝ) + η) < ε / 2 := by nlinarith + have hhigh : c * (η : ℝ) < ε := hsmall.trans (by linarith) + obtain ⟨τ, hτ, hτquarter, e, he⟩ := hpool n (η : ℝ) hη0 z + refine ⟨η, hη, hbudget, τ, hτ, hτquarter, e, ?_⟩ + have hpools := tendsto_blockSize_nat.eventually he + have hlists := SparseListConstruction.eventually_construct_good τ η hτ hη + have hwager := StageWeights.eventually_family_supportWager_bound_lt (n + 1) + (show 0 < ε / 2 by positivity) + filter_upwards [hpools, hlists, hwager, eventually_ge_atTop 1] with r hpr hlr hwr hr + obtain ⟨G, hGeval, hG, hGA⟩ := hpr + obtain ⟨L, hL, hgood⟩ := hlr + have hrpos : 0 < r := hr + have hJ : 0 < SparseParameters.listSize r := by + unfold SparseParameters.listSize SparseParameters.blockSize + positivity + let := PrefixStage.law_isProbabilityMeasure B hdis n + obtain ⟨q, hq⟩ := exists_candidate_joint_bound_of_goodPool (PrefixStage.law B n) + hgood hJ hη.le s H (fun i _ => hH i) (η : ℝ) hG (fun _ _ => 0) hd.le + have hscore : (∑ i : Fin (n + 1), + (wagerCost (PrefixStage.law B n) (s i) (candidate hG.1 hG.2.1 hL q 0) + + d * lowDropCost (H i)ᶜ (s i) (candidate hG.1 hG.2.1 hL q 0))) < ε := by + apply lt_of_le_of_lt hq + rw [StageWeights.polynomial_supportWager_bound_eq] + dsimp [c] at hbudget + nlinarith + refine ⟨G, L, hG, hL, hGeval, hGA, q, hrpos, ?_, ?_, ?_⟩ + · have hlen : L.length = r ^ 24 := by + rw [hgood.1] + simp only [SparseParameters.listSize, SparseParameters.blockSize, ← pow_mul] + exact q.isLt.trans_eq hlen + · intro a ha + exact (highMiss_sum_lt_of_goodPool s H hH B hdis n hG a ha).trans hhigh + · intro y + apply sums_lt_of_joint_score s H hH B hdis n + exact hscore + + +/-- Rank selection retains the supplied coordinate restriction. -/ +theorem exists_prepared (s : ℕ → BettingStrategy) + (H : ℕ → Set Cantor) (hH : ∀ i, MeasurableSet (H i)) + (A : ℕ → ℕ → Prop) (hpool : PoolSupply s H A) : + ∀ (old : ℕ → AffineBlock), + Pairwise (fun i j => Disjoint (old i).support (old j).support) → + ∀ (n z : ℕ) (error : ℚ), 0 < error → + ∃ P : Prepared s H old n z error, ∀ b ∈ P.pool, A n b := by + have hstage := eventual_candidates s H hH A hpool + intro old hold n z error he + have heR : (0 : ℝ) < error := by exact_mod_cast he + obtain ⟨η, hη, _, τ, hτ, hτlt, poolProgram, heventually⟩ := + hstage old hold n z (error : ℝ) heR + obtain ⟨program, hprogram⟩ := StageReconstruction.exists_fixed_program + (protectedRules s n) (StagePrefixCode.prefixHeader old n) poolProgram error τ η + have hlength := StageProgramLength.eventually_programFor_stage_budget + program (StageHorizon.adviceBound error (n + 1)) n + obtain ⟨r, hr, hbudget⟩ := (heventually.and hlength).exists + obtain ⟨G, L, hG, hL, hGeval, hGA, q, hrpos, hq, hhigh, hscores⟩ := hr + exact ⟨{ + listError := η + density := τ + listError_pos := hη + density_pos := hτ + density_lt := hτlt + poolProgram := poolProgram + program := program + rank := r + pool := G + candidates := L + goodPool := hG + list_eval := hL + pool_eval := hGeval + index := q + rank_pos := hrpos + index_lt := hq + program_correct := hprogram + program_budget := fun b hb => hbudget q.val b hq hb + high_miss := hhigh + scores := hscores }, hGA⟩ + + +/-- Every finite history has a successful extension confined to the supplied +coordinate set. The syndrome and all finite advice are still computed by the +original reconstruction program. -/ +theorem exists_step (s : ℕ → BettingStrategy) + (H : ℕ → Set Cantor) (hH : ∀ i, MeasurableSet (H i)) + (A : ℕ → ℕ → Prop) (hpool : PoolSupply s H A) + (old : ℕ → AffineBlock) + (hold : Pairwise (fun i j => Disjoint (old i).support (old j).support)) + (n z : ℕ) : + ∃ C V, StageRecursion.Step s H old n z (StageErrorBudget.rational n) C V ∧ + ∀ p ∈ C.support, A n p := by + let z' := max z ((PrefixStage.prefixSupport old n).sup id + 1) + have hz : ∀ k < n, ∀ p ∈ (old k).support, p < z' := by + intro k hk p hp + have hmem : p ∈ PrefixStage.prefixSupport old n := + (PrefixStage.mem_prefixSupport old n p).mpr ⟨k, hk, hp⟩ + have hle : p ≤ (PrefixStage.prefixSupport old n).sup id := + Finset.le_sup (f := id) hmem + exact lt_of_lt_of_le (Nat.lt_succ_of_le hle) (le_max_right _ _) + obtain ⟨P, hPA⟩ := exists_prepared s H hH A hpool old hold n z' + (StageErrorBudget.rational n) (StageErrorBudget.rational_pos n) + obtain ⟨R⟩ := StageOneStep.result_of_prepared s H old hold n z' + (StageErrorBudget.rational_pos n) P hz + have hstep := R.to_step P.goodPool.2.2.1 + refine ⟨R.block, R.horizon, { hstep with above := ?_ }, ?_⟩ + · intro p hp + exact (le_max_left z _).trans (hstep.above p hp) + · intro p hp + exact hPA p (List.mem_toFinset.mp (R.support_subset hp)) + +/-- The complete construction retains confinement along with all original +stage estimates and exact short affine descriptions. -/ +theorem exists_sequence (s : ℕ → BettingStrategy) + (H : ℕ → Set Cantor) (hH : ∀ i, MeasurableSet (H i)) + (A : ℕ → ℕ → Prop) (hpool : PoolSupply s H A) : + ∃ (B : ℕ → AffineBlock) (V : ℕ → ℕ), + Pairwise (fun i j => Disjoint (B i).support (B j).support) ∧ + (∀ n, ∀ p ∈ (B n).support, A n p) ∧ + (∀ i, StageEstimates B (s i).normalize.scan + (s i).normalize.capital.wager V (H i) i) ∧ + ∀ n : ℕ, ∃ (p : List Bool) (c : AffineCode.Data), + c ∈ AffineDescription.run p ∧ AffineCode.valid c = true ∧ + 2 * p.length + n + 1 ≤ AffineCode.rank c ∧ AffineCode.event c = (B n).event := + ConfinedStageRecursion.exists_sequence s H A (exists_step s H hH A hpool) hH + +end Klr.ConfinedStageConstruction diff --git a/LeanPool/KLRandomness/ConfinedStageRecursion.lean b/LeanPool/KLRandomness/ConfinedStageRecursion.lean new file mode 100644 index 0000000000..93c776488e --- /dev/null +++ b/LeanPool/KLRandomness/ConfinedStageRecursion.lean @@ -0,0 +1,213 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.StageRecursion +public import LeanPool.KLRandomness.StageRationalError + +/-! +# Dependent stage recursion preserving coordinate restrictions + +Starting from a concrete one-step extension theorem, dependent recursion +builds coherent finite histories. Their diagonal sequence has disjoint +supports, satisfies the actual `StageEstimates` for each eventually protected +strategy, and has a short exact affine program at every test level. + +The coordinate invariant is part of the selected extension before classical +choice is applied. Merely proving a stronger existence theorem and then +choosing from the weaker step relation would lose this invariant. +-/ + +@[expose] public section + +noncomputable section + +namespace Klr.ConfinedStageRecursion + +open MeasureTheory ProbabilityTheory StageRecursion +open scoped ENNReal + +/-- A selected actual extension of one finite history. -/ +structure Chosen (s : ℕ → BettingStrategy) (H : ℕ → Set Cantor) + (A : ℕ → ℕ → Prop) {n : ℕ} (h : History n) where + /-- The affine block supported in the prescribed coordinates for this stage. -/ + block : AffineBlock + /-- Finite query horizon established with this block. -/ + horizon : ℕ + specification : Step s H h.blocks n (h.cutoff s) + (StageErrorBudget.rational n) block horizon + confined : ∀ p ∈ block.support, A n p + +variable (s : ℕ → BettingStrategy) (H : ℕ → Set Cantor) + (A : ℕ → ℕ → Prop) + (hstep : ∀ (old : ℕ → AffineBlock), + Pairwise (fun i j => Disjoint (old i).support (old j).support) → + ∀ n z : ℕ, ∃ (C : AffineBlock) (V : ℕ), + Step s H old n z (StageErrorBudget.rational n) C V ∧ + ∀ p ∈ C.support, A n p) + +/-- Choice is used only to assemble the mathematical sequence from the +proved nonempty family of successful finite extensions. -/ +def chooseNext {n : ℕ} (h : History n) : Chosen s H A h := + Classical.choice (by + obtain ⟨C, V, hCV, hCA⟩ := hstep h.blocks h.disjoint n (h.cutoff s) + exact ⟨⟨C, V, hCV, hCA⟩⟩) + +/-- The recursively constructed, padded finite history. -/ +def histories : (n : ℕ) → History n + | 0 => History.empty + | n + 1 => + let h := histories n + let c := chooseNext s H A hstep h + h.extend s c.block c.horizon c.specification.above + +/-- The actual new block selected at each stage. -/ +def blocks (n : ℕ) : AffineBlock := (chooseNext s H A hstep (histories s H A hstep n)).block + +/-- The common protected-scan horizon selected at each stage. -/ +def horizons (n : ℕ) : ℕ := (chooseNext s H A hstep (histories s H A hstep n)).horizon + +theorem histories_succ_blocks (n : ℕ) : + (histories s H A hstep (n + 1)).blocks = + Function.update (histories s H A hstep n).blocks n (blocks s H A hstep n) := rfl + +theorem histories_succ_horizon (n : ℕ) : + (histories s H A hstep (n + 1)).horizon = + Function.update (histories s H A hstep n).horizon n (horizons s H A hstep n) := rfl + +/-- Every finite history is the exact initial segment of the diagonal blocks. -/ +theorem histories_blocks_eq (n j : ℕ) (hj : j < n) : + (histories s H A hstep n).blocks j = blocks s H A hstep j := by + induction n with + | zero => omega + | succ n ih => + rw [histories_succ_blocks] + by_cases hjn : j = n + · subst j + exact Function.update_self _ _ _ + · rw [Function.update_of_ne hjn] + exact ih (by omega) + +/-- The selected horizons have the same coherence property. -/ +theorem histories_horizon_eq (n j : ℕ) (hj : j < n) : + (histories s H A hstep n).horizon j = horizons s H A hstep j := by + induction n with + | zero => omega + | succ n ih => + rw [histories_succ_horizon] + by_cases hjn : j = n + · subst j + exact Function.update_self _ _ _ + · rw [Function.update_of_ne hjn] + exact ih (by omega) + +/-- All preceding finite-stage laws agree exactly with the laws of the +diagonal sequence, including laws strictly before the latest history. -/ +theorem histories_law_eq (n a : ℕ) (ha : a ≤ n) : + PrefixStage.law (histories s H A hstep n).blocks a = + PrefixStage.law (blocks s H A hstep) a := by + apply congrArg AffineBlock.finiteStageLaw + funext j + exact histories_blocks_eq s H A hstep n j.val (lt_of_lt_of_le j.isLt ha) + +theorem blocks_pairwise : + Pairwise (fun i j => Disjoint (blocks s H A hstep i).support + (blocks s H A hstep j).support) := by + intro i j hij + have hi : i < max i j + 1 := Nat.lt_succ_of_le (le_max_left _ _) + have hj : j < max i j + 1 := Nat.lt_succ_of_le (le_max_right _ _) + have hd := (histories s H A hstep (max i j + 1)).disjoint hij + dsimp only at hd + rwa [histories_blocks_eq s H A hstep _ i hi, histories_blocks_eq s H A hstep _ j hj] at hd + +theorem selected_step (n : ℕ) : + Step s H (histories s H A hstep n).blocks n ((histories s H A hstep n).cutoff s) + (StageErrorBudget.rational n) (blocks s H A hstep n) (horizons s H A hstep n) := + (chooseNext s H A hstep (histories s H A hstep n)).specification + +/-- Coordinate restrictions survive the choice of the actual diagonal block. -/ +theorem blocks_confined (n : ℕ) : + ∀ p ∈ (blocks s H A hstep n).support, A n p := + (chooseNext s H A hstep (histories s H A hstep n)).confined + +/-- The early wager of one block depends only on that block and its horizon. -/ +theorem earlyWager_single (B : ℕ → AffineBlock) (π : ScanRule) + (w : List Bool → ℝ) (V : ℕ → ℕ) (j : ℕ) : + EarlyLateWagers.earlyWager (fun _ => B j) π w (fun _ => V j) 0 = + EarlyLateWagers.earlyWager B π w V j := rfl + +/-- Later blocks avoid every branch through every earlier protected horizon. -/ +theorem horizon_avoidance (i j k : ℕ) (hij : i ≤ j) (hjk : j < k) + (v : List Bool) (hv : v.length = horizons s H A hstep j) : + (blocks s H A hstep k).UnreadFullRank (s i).normalize.scan v := by + apply HorizonAvoidance.unreadFullRank_of_queryBound_le _ _ (horizons s H A hstep j) _ v hv.le + intro q hq + have hb := History.queryBound_le_cutoff s (histories s H A hstep k) ⟨j, hjk⟩ i hij + rw [histories_horizon_eq s H A hstep k j hjk] at hb + exact hb.trans ((selected_step s H A hstep k).above q hq) + +/-- The finite construction yields all actual stage estimates for strategy +`i` from stage `i` onward. -/ +theorem stageEstimates (hH : ∀ i, MeasurableSet (H i)) (i : ℕ) : + StageEstimates (blocks s H A hstep) (s i).normalize.scan + (s i).normalize.capital.wager (horizons s H A hstep) (H i) i := by + refine ⟨hH i, ?_, ?_, ?_, ?_, ?_⟩ + · intro j hij v hv k hjk + exact horizon_avoidance s H A hstep i j k hij hjk v hv + · intro j hij + have h := (selected_step s H A hstep j).early_and_partial i hij + rw [histories_law_eq s H A hstep j j le_rfl, + ← PrefixStage.law_succ_eq_cond, earlyWager_single] at h + have hb : ENNReal.ofReal (4 * (StageErrorBudget.rational j : ℝ)) = + 4 * StageErrorBudget.error j := by + simpa only [Nat.cast_ofNat] using StageErrorBudget.ofReal_mul_rational 4 j + rwa [hb] at h + · intro j hij + have h := (selected_step s H A hstep j).first_drop_tail i hij + rw [histories_law_eq s H A hstep j j le_rfl, + ← PrefixStage.law_succ_eq_cond] at h + have hb : ENNReal.ofReal (2 * (StageErrorBudget.rational j : ℝ)) = + 2 * StageErrorBudget.error j := by + simpa only [Nat.cast_ofNat] using StageErrorBudget.ofReal_mul_rational 2 j + rwa [hb] at h + · intro j hij + have h := (selected_step s H A hstep j).high_no_drop i hij + rwa [histories_law_eq s H A hstep j j le_rfl, StageErrorBudget.ofReal_rational] at h + · intro j hij k hjk + have h := (selected_step s H A hstep k).earlier_low_drop + (j + 1) (by omega) i (by omega) + rwa [histories_law_eq s H A hstep k (j + 1) (by omega), + StageErrorBudget.ofReal_rational] at h + +/-- Stage `n` supplies the exact short affine program required at test level `n`. -/ +theorem description (n : ℕ) : ∃ (p : List Bool) (c : AffineCode.Data), + c ∈ AffineDescription.run p ∧ AffineCode.valid c = true ∧ + AffineCode.rank c = (blocks s H A hstep n).rank ∧ + 2 * p.length + n + 1 ≤ AffineCode.rank c ∧ + AffineCode.event c = (blocks s H A hstep n).event := + (selected_step s H A hstep n).description + +include hstep in +/-- The concrete one-stage extension relation glues to a full sequence +with the probabilistic estimates and exact description obligations discharged. -/ +theorem exists_sequence (hH : ∀ i, MeasurableSet (H i)) : + ∃ (B : ℕ → AffineBlock) (V : ℕ → ℕ), + Pairwise (fun i j => Disjoint (B i).support (B j).support) ∧ + (∀ n, ∀ p ∈ (B n).support, A n p) ∧ + (∀ i, StageEstimates B (s i).normalize.scan (s i).normalize.capital.wager V (H i) i) ∧ + ∀ n : ℕ, ∃ (p : List Bool) (c : AffineCode.Data), + c ∈ AffineDescription.run p ∧ AffineCode.valid c = true ∧ + 2 * p.length + n + 1 ≤ AffineCode.rank c ∧ AffineCode.event c = (B n).event := by + refine ⟨blocks s H A hstep, horizons s H A hstep, blocks_pairwise s H A hstep, + blocks_confined s H A hstep, stageEstimates s H A hstep hH, ?_⟩ + intro n + obtain ⟨p, c, hp, hc, _, hb, he⟩ := description s H A hstep n + exact ⟨p, c, hp, hc, hb, he⟩ + +end Klr.ConfinedStageRecursion diff --git a/LeanPool/KLRandomness/DescriptionBudget.lean b/LeanPool/KLRandomness/DescriptionBudget.lean new file mode 100644 index 0000000000..c8ed8a2167 --- /dev/null +++ b/LeanPool/KLRandomness/DescriptionBudget.lean @@ -0,0 +1,128 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.MartinLof +public import LeanPool.KLRandomness.EffectiveSearch +public import Mathlib.Data.List.OfFn +import Mathlib.Tactic.NormNum + +/-! +# Measure budgets for plain binary descriptions + +There are `2^d` binary programs of length `d`. Consequently charging each +program of length `d` a measure budget `2^(-(2*d+n+1))` gives a total budget +`2^(-n)`. This uses all binary strings, with no prefix-free assumption. + +The measure-budget results are modular. `Klr.AffineDescription` instantiates +them with a concrete interpreter and effective affine verifier. Descriptions +of the particular systems chosen in Liu and Meng's construction still require +the stage reconstruction algorithm and its advice bounds. +-/ + +@[expose] public section + +namespace Klr + +open MeasureTheory +open scoped ENNReal + +/-- The exact budget assigned to all plain binary descriptions. -/ +theorem tsum_binary_description_budget (n : ℕ) : + (∑' p : List Bool, (1 / 2 : ℝ≥0∞) ^ (2 * p.length + n + 1)) = + (1 / 2 : ℝ≥0∞) ^ n := by + have by_length : + (∑' p : List Bool, (1 / 2 : ℝ≥0∞) ^ (2 * p.length + n + 1)) = + ∑' d : ℕ, ∑' _ : Fin d → Bool, (1 / 2 : ℝ≥0∞) ^ (2 * d + n + 1) := by + rw [← (List.equivSigmaTuple (α := Bool)).symm.tsum_eq + (fun p : List Bool => (1 / 2 : ℝ≥0∞) ^ (2 * p.length + n + 1))] + simpa using tsum_sigma (fun d (_ : Fin d → Bool) => + (1 / 2 : ℝ≥0∞) ^ (2 * d + n + 1)) + rw [by_length] + have term (d : ℕ) : + (∑' _ : Fin d → Bool, (1 / 2 : ℝ≥0∞) ^ (2 * d + n + 1)) = + (1 / 2 : ℝ≥0∞) ^ (d + n + 1) := by + simp only [tsum_fintype, Finset.sum_const, Finset.card_univ, nsmul_eq_mul, + Fintype.card_fun, Fintype.card_bool, Fintype.card_fin, Nat.cast_pow, Nat.cast_ofNat] + rw [show 2 * d + n + 1 = d + (d + n + 1) by omega, pow_add, + ← mul_assoc, ← mul_pow] + rw [show (2 : ℝ≥0∞) * (1 / 2) = 1 by + simpa only [one_div] using ENNReal.mul_inv_cancel + (by norm_num : (2 : ℝ≥0∞) ≠ 0) (by norm_num : (2 : ℝ≥0∞) ≠ ∞)] + simp + simp_rw [term, show ∀ d : ℕ, d + n + 1 = d + (n + 1) by omega, pow_add] + rw [ENNReal.tsum_mul_right, ENNReal.tsum_geometric, pow_succ] + norm_num + calc + _ = ((2 : ℝ≥0∞) * 2⁻¹) * 2⁻¹ ^ n := by ac_rfl + _ = _ := by rw [ENNReal.mul_inv_cancel (by norm_num) (by norm_num), one_mul] + +/-- Countable subadditivity turns the per-description budgets into a test-level bound. -/ +theorem measure_iUnion_le_description_budget {Ω : Type*} [MeasurableSpace Ω] + (μ : Measure Ω) (E : List Bool → Set Ω) (n : ℕ) + (hE : ∀ p, μ (E p) ≤ (1 / 2 : ℝ≥0∞) ^ (2 * p.length + n + 1)) : + μ (⋃ p, E p) ≤ (1 / 2 : ℝ≥0∞) ^ n := by + calc + μ (⋃ p, E p) ≤ ∑' p, μ (E p) := measure_iUnion_le E + _ ≤ ∑' p : List Bool, (1 / 2 : ℝ≥0∞) ^ (2 * p.length + n + 1) := tsum_le_tsum hE + _ = _ := tsum_binary_description_budget n + +/-- One test level, formed by taking the union of the events described by all programs. -/ +def descriptionLevel (W : ℕ × List Bool × List Bool → Prop) (n : ℕ) : Set Cantor := + ⋃ p : List Bool, cylinderUnion (fun s => W (n, p, s)) + +/-- A single c.e. predicate on `(level, program, cylinder)` yields uniformly effective levels. -/ +theorem descriptionLevel_uniform {W : ℕ × List Bool × List Bool → Prop} + (hW : REPred W) : IsUniformlyEffectivelyOpen (descriptionLevel W) := by + have hc : Computable (fun a : (ℕ × List Bool) × List Bool => (a.1.1, a.2, a.1.2)) := + (Computable.fst.comp Computable.fst).pair + (Computable.snd.pair (Computable.snd.comp Computable.fst)) + have hV : REPred (fun a : ℕ × List Bool => ∃ p : List Bool, W (a.1, p, a.2)) := + rePred_exists (hW.comp hc) + refine ⟨_, hV, fun n => ?_⟩ + ext X + simp only [descriptionLevel, Set.mem_iUnion, cylinderUnion, Set.mem_ofPred_eq] + constructor + · rintro ⟨p, s, hps, hs⟩ + exact ⟨s, ⟨p, hps⟩, hs⟩ + · rintro ⟨s, ⟨p, hps⟩, hs⟩ + exact ⟨p, s, hps, hs⟩ + +/-- The Section 3 description budget supplies the required bound at each level. -/ +theorem descriptionLevel_measure_le (W : ℕ × List Bool × List Bool → Prop) (n : ℕ) + (hbound : ∀ p : List Bool, fairCoin (cylinderUnion (fun s => W (n, p, s))) ≤ + (1 / 2 : ℝ≥0∞) ^ (2 * p.length + n + 1)) : + fairCoin (descriptionLevel W n) ≤ (1 / 2 : ℝ≥0∞) ^ n := + measure_iUnion_le_description_budget fairCoin _ n hbound + +/-- A uniformly c.e. family with these per-program budgets defines a genuine Martin-Löf test. +The concrete affine-system instance is supplied by `Klr.AffineDescription`. -/ +theorem exists_martinLofTest_of_description_family + {W : ℕ × List Bool × List Bool → Prop} (hW : REPred W) + (hbound : ∀ (n : ℕ) (p : List Bool), + fairCoin (cylinderUnion (fun s => W (n, p, s))) ≤ + (1 / 2 : ℝ≥0∞) ^ (2 * p.length + n + 1)) : + ∃ T : MartinLofTest, ∀ n, T.level n = descriptionLevel W n := by + exact MartinLofTest.exists_of_uniform (descriptionLevel_uniform hW) + (fun n => descriptionLevel_measure_le W n (hbound n)) + +/-- Membership in some sufficiently small described event at every level witnesses nonrandomness. -/ +theorem not_martinLofRandom_of_descriptions + {W : ℕ × List Bool × List Bool → Prop} (hW : REPred W) + (hbound : ∀ (n : ℕ) (p : List Bool), + fairCoin (cylinderUnion (fun s => W (n, p, s))) ≤ + (1 / 2 : ℝ≥0∞) ^ (2 * p.length + n + 1)) + {X : Cantor} (hX : ∀ n, ∃ p, X ∈ cylinderUnion (fun s => W (n, p, s))) : + ¬MartinLofRandom X := by + apply not_martinLofRandom_of_uniform (descriptionLevel_uniform hW) + (fun n => descriptionLevel_measure_le W n (hbound n)) + intro n + exact Set.mem_iUnion.mpr (hX n) + +end Klr diff --git a/LeanPool/KLRandomness/DropEvents.lean b/LeanPool/KLRandomness/DropEvents.lean new file mode 100644 index 0000000000..d264a9e831 --- /dev/null +++ b/LeanPool/KLRandomness/DropEvents.lean @@ -0,0 +1,126 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.BlockProductAnswer +import Mathlib.Tactic.Measurability + +/-! +# Actual rank-drop events along fresh scans + +Times are zero based: `atTime B π j X t` concerns the query made after `t` +answers, and compares the unread ranks after `t + 1` and `t` answers. Thus +`lateEvent B π V j` means that block `j` has a rank drop after its first +`V j` queries have been answered. These are events of actual input paths, +with no stopping-time or measurability hypotheses left to the caller. +-/ + +@[expose] public section + +namespace Klr.DropEvents + +open MeasureTheory AffineObservation + +/-- A rank-losing next query belonging to the specified block. -/ +def atBlock (B : ℕ → AffineBlock) (π : ScanRule) (j : ℕ) (v : List Bool) : Prop := + π.query v ∈ (B j).support ∧ + (B j).remainingRank π (v ++ [false]) < (B j).remainingRank π v + +/-- The actual query at time `t` causes a rank drop in block `j`. -/ +def atTime (B : ℕ → AffineBlock) (π : ScanRule) (j : ℕ) (X : Cantor) (t : ℕ) : Prop := + atBlock B π j (π.transcript X t) + +/-- At least one drop in block `j` occurs at or after its prescribed horizon. -/ +def lateEvent (B : ℕ → AffineBlock) (π : ScanRule) (V : ℕ → ℕ) (j : ℕ) : Set Cantor := + {X | ∃ t, V j ≤ t ∧ atTime B π j X t} + +theorem forced_iff (B : ℕ → AffineBlock) (π : ScanRule) (v : List Bool) : + BlockProductAnswer.forced B π v ↔ ∃ j, atBlock B π j v := Iff.rfl + +/-- A query outside a block cannot change its unread rank. -/ +theorem remainingRank_snoc_of_query_not_mem (B : AffineBlock) (π : ScanRule) + (v : List Bool) (hq : π.query v ∉ B.support) (b : Bool) : + B.remainingRank π (v ++ [b]) = B.remainingRank π v := by + apply congrArg (fun S : Submodule (ZMod 2) (Fin B.rank → ZMod 2) => + Module.finrank (ZMod 2) S) + apply AffineAnswer.unreadMap_range_congr + ext i + have hi : (i : ℕ) ≠ π.query v := fun h => hq (h ▸ i.property) + simp [AffineBlock.observed, π.queriedPositions_snoc, hi] + +/-- The predictable false-answer definition is exactly the actual numerical rank drop. -/ +theorem atTime_iff_rank_drop (B : ℕ → AffineBlock) (π : ScanRule) + (j : ℕ) (X : Cantor) (t : ℕ) : + atTime B π j X t ↔ + (B j).remainingRank π (π.transcript X (t + 1)) < + (B j).remainingRank π (π.transcript X t) := by + rw [ScanRule.transcript_succ, + (B j).remainingRank_snoc_answer_independent π _ _ false] + constructor + · exact fun h => h.2 + · intro h + refine ⟨?_, h⟩ + by_contra hq + rw [remainingRank_snoc_of_query_not_mem (B j) π _ hq false] at h + exact lt_irrefl _ h + +/-- A function of any fixed finite transcript is measurable, even when the function +on transcripts is noncomputable. Its domain of possible transcripts is countable. -/ +theorem measurable_transcript_eval {α : Type*} [MeasurableSpace α] + (π : ScanRule) (n : ℕ) (f : List Bool → α) : + Measurable (fun X : Cantor => f (π.transcript X n)) := by + let : MeasurableSpace (List Bool) := ⊤ + have ht : Measurable (fun X : Cantor => π.transcript X n) := by + apply measurable_to_countable' + intro v + by_cases hv : v.length = n + · change MeasurableSet {X : Cantor | π.transcript X n = v} + simpa only [hv] using π.measurableSet_transcript v + · have hempty : (fun X : Cantor => π.transcript X n) ⁻¹' {v} = ∅ := by + ext X + simp only [Set.mem_preimage, Set.mem_singleton_iff, Set.mem_empty_iff_false, + iff_false] + intro h + exact hv (by rw [← h, π.length_transcript]) + rw [hempty] + exact MeasurableSet.empty + exact Measurable.of_discrete.comp ht + +theorem measurableSet_transcript_pred (π : ScanRule) (n : ℕ) (P : List Bool → Prop) : + MeasurableSet {X : Cantor | P (π.transcript X n)} := by + classical + have h := measurable_transcript_eval π n (fun v => decide (P v)) + have he : MeasurableSet {X : Cantor | decide (P (π.transcript X n)) = true} := + h (measurableSet_singleton true) + simpa only [decide_eq_true_eq] using he + +theorem measurableSet_atTime (B : ℕ → AffineBlock) (π : ScanRule) (j t : ℕ) : + MeasurableSet {X | atTime B π j X t} := + measurableSet_transcript_pred π t (atBlock B π j) + +theorem measurableSet_lateEvent (B : ℕ → AffineBlock) (π : ScanRule) + (V : ℕ → ℕ) (j : ℕ) : MeasurableSet (lateEvent B π V j) := by + have he : lateEvent B π V j = ⋃ t : {t : ℕ // V j ≤ t}, + {X | atTime B π j X t.val} := by + ext X + simp only [lateEvent, Set.mem_ofPred_eq, Set.mem_iUnion] + exact ⟨fun ⟨t, ht, hd⟩ => ⟨⟨t, ht⟩, hd⟩, + fun ⟨t, hd⟩ => ⟨t.val, t.property, hd⟩⟩ + rw [he] + exact MeasurableSet.iUnion fun t => measurableSet_atTime B π j t.val + +/-- Freshness alone makes the set of all drops in any fixed block finite. -/ +theorem finite_drop_times (B : ℕ → AffineBlock) (π : ScanRule) (j : ℕ) (X : Cantor) : + {t | atTime B π j X t}.Finite := by + have hf : ((fun t => π.query (π.transcript X t)) ⁻¹' + ((B j).support : Set ℕ)).Finite := + (B j).support.finite_toSet.preimage (π.query_injective X).injOn + exact hf.subset fun _ ht => ht.1 + +end Klr.DropEvents diff --git a/LeanPool/KLRandomness/EarlyLateWagers.lean b/LeanPool/KLRandomness/EarlyLateWagers.lean new file mode 100644 index 0000000000..6f03063cc7 --- /dev/null +++ b/LeanPool/KLRandomness/EarlyLateWagers.lean @@ -0,0 +1,349 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.DropEvents +public import Mathlib.MeasureTheory.OuterMeasure.BorelCantelli +public import Mathlib.MeasureTheory.Integral.Lebesgue.Markov +import Mathlib.Tactic.NormNum +import Mathlib.Tactic.Positivity + +/-! +# Summability of actual forced wagers from early and late estimates + +For each block, the early contribution is the finite sum of absolute wagers +at that block's actual rank-drop queries before its prescribed horizon. A +finite sum of the expectations of these contributions makes their total +finite almost surely. A summable sequence of late-drop probabilities leaves +only finitely many late blocks by Borel–Cantelli; freshness and finite block +supports then leave only finitely many late queries. + +The main theorem concludes summability on all actual forced queries. The +two quantitative hypotheses remain application obligations: this file does +not construct blocks satisfying the paper's stage estimates. Neither +disjointness of the blocks nor a uniform bound on the wagers is needed for +this implication. +-/ + +@[expose] public section + +namespace Klr.EarlyLateWagers + +open MeasureTheory DropEvents +open scoped ENNReal + +/-- The absolute wager at a rank drop in one specified block, and zero otherwise. -/ +noncomputable def blockWager (B : ℕ → AffineBlock) (π : ScanRule) + (w : List Bool → ℝ) (j : ℕ) (X : Cantor) (t : ℕ) : ℝ := by + classical + exact if atTime B π j X t then |w (π.transcript X t)| else 0 + +/-- The actual early rank-drop wager mass in block `j`. -/ +noncomputable def earlyWager (B : ℕ → AffineBlock) (π : ScanRule) + (w : List Bool → ℝ) (V : ℕ → ℕ) (j : ℕ) (X : Cantor) : ℝ := + ∑ t ∈ Finset.range (V j), blockWager B π w j X t + +/-- The actual absolute wager series restricted to rank-drop queries. -/ +noncomputable def forcedWager (B : ℕ → AffineBlock) (π : ScanRule) + (w : List Bool → ℝ) (X : Cantor) (t : ℕ) : ℝ := by + classical + exact if BlockProductAnswer.forced B π (π.transcript X t) + then |w (π.transcript X t)| else 0 + +/-- A query counted once whenever it is early for some block in which it loses rank. -/ +noncomputable def earlyPart (B : ℕ → AffineBlock) (π : ScanRule) + (w : List Bool → ℝ) (V : ℕ → ℕ) (X : Cantor) (t : ℕ) : ℝ := by + classical + exact if ∃ j, t < V j ∧ atTime B π j X t then |w (π.transcript X t)| else 0 + +/-- A query counted once whenever it is late for some block in which it loses rank. -/ +noncomputable def latePart (B : ℕ → AffineBlock) (π : ScanRule) + (w : List Bool → ℝ) (V : ℕ → ℕ) (X : Cantor) (t : ℕ) : ℝ := by + classical + exact if ∃ j, V j ≤ t ∧ atTime B π j X t then |w (π.transcript X t)| else 0 + +/-- The nonnegative two-index array used to sum early contributions. -/ +noncomputable def earlyTerm (B : ℕ → AffineBlock) (π : ScanRule) + (w : List Bool → ℝ) (V : ℕ → ℕ) (X : Cantor) (j t : ℕ) : ℝ≥0∞ := by + classical + exact if t < V j ∧ atTime B π j X t then ENNReal.ofReal |w (π.transcript X t)| else 0 + +theorem blockWager_nonneg (B : ℕ → AffineBlock) (π : ScanRule) + (w : List Bool → ℝ) (j : ℕ) (X : Cantor) (t : ℕ) : + 0 ≤ blockWager B π w j X t := by + classical + unfold blockWager + split_ifs <;> positivity + +theorem earlyWager_nonneg (B : ℕ → AffineBlock) (π : ScanRule) + (w : List Bool → ℝ) (V : ℕ → ℕ) (j : ℕ) (X : Cantor) : + 0 ≤ earlyWager B π w V j X := + Finset.sum_nonneg fun t _ => blockWager_nonneg B π w j X t + +theorem earlyPart_nonneg (B : ℕ → AffineBlock) (π : ScanRule) + (w : List Bool → ℝ) (V : ℕ → ℕ) (X : Cantor) (t : ℕ) : + 0 ≤ earlyPart B π w V X t := by + classical + unfold earlyPart + split_ifs <;> positivity + +theorem latePart_nonneg (B : ℕ → AffineBlock) (π : ScanRule) + (w : List Bool → ℝ) (V : ℕ → ℕ) (X : Cantor) (t : ℕ) : + 0 ≤ latePart B π w V X t := by + classical + unfold latePart + split_ifs <;> positivity + +theorem forcedWager_nonneg (B : ℕ → AffineBlock) (π : ScanRule) + (w : List Bool → ℝ) (X : Cantor) (t : ℕ) : + 0 ≤ forcedWager B π w X t := by + classical + unfold forcedWager + split_ifs <;> positivity + +theorem measurable_blockWager (B : ℕ → AffineBlock) (π : ScanRule) + (w : List Bool → ℝ) (j t : ℕ) : + Measurable (fun X => blockWager B π w j X t) := by + classical + exact measurable_transcript_eval π t + (fun v => if atBlock B π j v then |w v| else 0) + +theorem measurable_earlyWager (B : ℕ → AffineBlock) (π : ScanRule) + (w : List Bool → ℝ) (V : ℕ → ℕ) (j : ℕ) : + Measurable (earlyWager B π w V j) := by + exact Finset.measurable_fun_sum _ fun t _ => measurable_blockWager B π w j t + +/-- A normalized strategy contributes at most one half per early query. -/ +theorem earlyWager_le_half_horizon (B : ℕ → AffineBlock) (π : ScanRule) + (w : List Bool → ℝ) (V : ℕ → ℕ) (hw : ∀ v, |w v| ≤ (1 / 2 : ℝ)) + (j : ℕ) (X : Cantor) : earlyWager B π w V j X ≤ (V j : ℝ) / 2 := by + classical + calc + earlyWager B π w V j X ≤ ∑ _t ∈ Finset.range (V j), (1 / 2 : ℝ) := by + apply Finset.sum_le_sum + intro t _ + unfold blockWager + split_ifs + · exact hw _ + · norm_num + _ = (V j : ℝ) / 2 := by simp [div_eq_mul_inv] + +/-- The finite-horizon bound also controls its lower Lebesgue integral. -/ +theorem lintegral_earlyWager_le (μ : Measure Cantor) (B : ℕ → AffineBlock) (π : ScanRule) + (w : List Bool → ℝ) (V : ℕ → ℕ) (hw : ∀ v, |w v| ≤ (1 / 2 : ℝ)) (j : ℕ) : + (∫⁻ X, ENNReal.ofReal (earlyWager B π w V j X) ∂μ) ≤ + ENNReal.ofReal ((V j : ℝ) / 2) * μ Set.univ := by + calc + _ ≤ ∫⁻ _X : Cantor, ENNReal.ofReal ((V j : ℝ) / 2) ∂μ := + lintegral_mono fun X => ENNReal.ofReal_le_ofReal (earlyWager_le_half_horizon B π w V hw j X) + _ = _ := lintegral_const _ + +/-- Initial finitely many blocks have finite early expectation under every finite law. -/ +theorem lintegral_earlyWager_lt_top (μ : Measure Cantor) [IsFiniteMeasure μ] + (B : ℕ → AffineBlock) (π : ScanRule) (w : List Bool → ℝ) (V : ℕ → ℕ) + (hw : ∀ v, |w v| ≤ (1 / 2 : ℝ)) (j : ℕ) : + (∫⁻ X, ENNReal.ofReal (earlyWager B π w V j X) ∂μ) < ∞ := + lt_of_le_of_lt (lintegral_earlyWager_le μ B π w V hw j) + (ENNReal.mul_lt_top ENNReal.ofReal_lt_top (measure_lt_top μ Set.univ)) + +/-- The inner series is precisely the prescribed finite early contribution. -/ +theorem tsum_earlyTerm (B : ℕ → AffineBlock) (π : ScanRule) + (w : List Bool → ℝ) (V : ℕ → ℕ) (X : Cantor) (j : ℕ) : + ∑' t, earlyTerm B π w V X j t = ENNReal.ofReal (earlyWager B π w V j X) := by + classical + rw [tsum_eq_sum (s := Finset.range (V j)) (fun t ht => by + simp only [Finset.mem_range] at ht + simp [earlyTerm, ht])] + rw [earlyWager, ENNReal.ofReal_sum_of_nonneg + (fun t _ => blockWager_nonneg B π w j X t)] + apply Finset.sum_congr rfl + intro t ht + have ht' := Finset.mem_range.mp ht + by_cases hd : atTime B π j X t <;> simp [earlyTerm, blockWager, ht', hd] + +/-- Counting a query once costs no more than summing its contributions over all blocks. -/ +theorem earlyPart_le_tsum (B : ℕ → AffineBlock) (π : ScanRule) + (w : List Bool → ℝ) (V : ℕ → ℕ) (X : Cantor) (t : ℕ) : + ENNReal.ofReal (earlyPart B π w V X t) ≤ ∑' j, earlyTerm B π w V X j t := by + classical + by_cases h : ∃ j, t < V j ∧ atTime B π j X t + · obtain ⟨j, hj⟩ := h + rw [earlyPart, ite_eq_left ⟨j, hj⟩] + calc + ENNReal.ofReal |w (π.transcript X t)| = earlyTerm B π w V X j t := by + simp [earlyTerm, hj] + _ ≤ ∑' k, earlyTerm B π w V X k t := + le_tsum (fun k => earlyTerm B π w V X k t) j + · simp [earlyPart, h] + +/-- Finite total early block mass implies summability of the actual early query series. -/ +theorem summable_earlyPart (B : ℕ → AffineBlock) (π : ScanRule) + (w : List Bool → ℝ) (V : ℕ → ℕ) (X : Cantor) + (h : (∑' j, ENNReal.ofReal (earlyWager B π w V j X)) < ∞) : + Summable (earlyPart B π w V X) := by + have hle : (∑' t, ENNReal.ofReal (earlyPart B π w V X t)) ≤ + ∑' j, ENNReal.ofReal (earlyWager B π w V j X) := by + calc + _ ≤ ∑' t, ∑' j, earlyTerm B π w V X j t := + tsum_le_tsum fun t => earlyPart_le_tsum B π w V X t + _ = ∑' j, ∑' t, earlyTerm B π w V X j t := tsum_comm + _ = _ := by simp only [tsum_earlyTerm] + have hs := ENNReal.summable_toReal (lt_of_le_of_lt hle h).ne + simpa only [ENNReal.toReal_ofReal (earlyPart_nonneg B π w V X _)] using hs + +/-- Finitely many late blocks give finitely many actual late queries. -/ +theorem finite_late_times (B : ℕ → AffineBlock) (π : ScanRule) + (V : ℕ → ℕ) (X : Cantor) (h : {j | X ∈ lateEvent B π V j}.Finite) : + {t | ∃ j, V j ≤ t ∧ atTime B π j X t}.Finite := by + have hf := h.biUnion (fun j _ => finite_drop_times B π j X) + apply hf.subset + rintro t ⟨j, hj, hd⟩ + exact Set.mem_iUnion.mpr ⟨j, Set.mem_iUnion.mpr ⟨⟨t, hj, hd⟩, hd⟩⟩ + +theorem summable_latePart (B : ℕ → AffineBlock) (π : ScanRule) + (w : List Bool → ℝ) (V : ℕ → ℕ) (X : Cantor) + (h : {j | X ∈ lateEvent B π V j}.Finite) : + Summable (latePart B π w V X) := by + classical + let S := (finite_late_times B π V X h).toFinset + apply summable_of_ne_finset_zero (s := S) + intro t ht + have hn : ¬∃ j, V j ≤ t ∧ atTime B π j X t := by + simpa only [S, Set.Finite.mem_toFinset, Set.mem_ofPred_eq] using ht + simp [latePart, hn] + +theorem forcedWager_le_parts (B : ℕ → AffineBlock) (π : ScanRule) + (w : List Bool → ℝ) (V : ℕ → ℕ) (X : Cantor) (t : ℕ) : + forcedWager B π w X t ≤ earlyPart B π w V X t + latePart B π w V X t := by + classical + by_cases h : BlockProductAnswer.forced B π (π.transcript X t) + · obtain ⟨j, hj⟩ := (forced_iff B π _).mp h + change atTime B π j X t at hj + rw [forcedWager, ite_eq_left h] + by_cases ht : t < V j + · have he : earlyPart B π w V X t = |w (π.transcript X t)| := by + exact ite_eq_left (show ∃ k, t < V k ∧ atTime B π k X t from ⟨j, ht, hj⟩) + rw [he] + exact le_add_of_nonneg_right (latePart_nonneg B π w V X t) + · have hl : latePart B π w V X t = |w (π.transcript X t)| := by + exact ite_eq_left + (show ∃ k, V k ≤ t ∧ atTime B π k X t from ⟨j, Nat.le_of_not_gt ht, hj⟩) + rw [hl] + exact le_add_of_nonneg_left (earlyPart_nonneg B π w V X t) + · rw [forcedWager, ite_eq_right h] + exact add_nonneg (earlyPart_nonneg B π w V X t) (latePart_nonneg B π w V X t) + +/-- Finite summed expectations imply almost-sure finiteness of total early block mass. -/ +theorem ae_early_total_lt_top (μ : Measure Cantor) (B : ℕ → AffineBlock) (π : ScanRule) + (w : List Bool → ℝ) (V : ℕ → ℕ) + (h : (∑' j, ∫⁻ X, ENNReal.ofReal (earlyWager B π w V j X) ∂μ) < ∞) : + ∀ᵐ X ∂μ, (∑' j, ENNReal.ofReal (earlyWager B π w V j X)) < ∞ := by + have hm : ∀ j, Measurable (fun X => ENNReal.ofReal (earlyWager B π w V j X)) := + fun j => (measurable_earlyWager B π w V j).ennreal_ofReal + apply ae_lt_top (Measurable.tsum hm) + rw [lintegral_tsum (fun j => (hm j).aemeasurable)] + exact h.ne + +/-- The paper's forced-wager summability conclusion from concrete early/late estimates. +All queries and weights in the hypotheses and conclusion refer to the actual scan path. -/ +theorem ae_summable_forcedWager (μ : Measure Cantor) (B : ℕ → AffineBlock) (π : ScanRule) + (w : List Bool → ℝ) (V : ℕ → ℕ) + (hlate : (∑' j, μ (lateEvent B π V j)) < ∞) + (hearly : (∑' j, ∫⁻ X, ENNReal.ofReal (earlyWager B π w V j X) ∂μ) < ∞) : + ∀ᵐ X ∂μ, Summable (forcedWager B π w X) := by + filter_upwards [ae_finite_setOfPred_mem hlate.ne, + ae_early_total_lt_top μ B π w V hearly] with X hXlate hXearly + apply Summable.of_nonneg_of_le (forcedWager_nonneg B π w X) + (forcedWager_le_parts B π w V X) + exact (summable_earlyPart B π w V X hXearly).add (summable_latePart B π w V X hXlate) + +/-- No estimates at all are required to sum the contribution of a single fixed block. -/ +theorem summable_blockWager (B : ℕ → AffineBlock) (π : ScanRule) + (w : List Bool → ℝ) (j : ℕ) (X : Cantor) : Summable (blockWager B π w j X) := by + classical + let S := (finite_drop_times B π j X).toFinset + apply summable_of_ne_finset_zero (s := S) + intro t ht + have hn : ¬atTime B π j X t := by + simpa only [S, Set.Finite.mem_toFinset, Set.mem_ofPred_eq] using ht + simp [blockWager, hn] + +/-- Deleting finitely many blocks does not change forced-wager summability. -/ +theorem summable_forcedWager_of_tail (B : ℕ → AffineBlock) (π : ScanRule) + (w : List Bool → ℝ) (X : Cantor) (J : ℕ) + (h : Summable (forcedWager (fun j => B (j + J)) π w X)) : + Summable (forcedWager B π w X) := by + classical + have hp : Summable (fun t => ∑ j ∈ Finset.range J, blockWager B π w j X t) := + summable_sum (fun j _ => summable_blockWager B π w j X) + apply Summable.of_nonneg_of_le (forcedWager_nonneg B π w X) _ (hp.add h) + intro t + change forcedWager B π w X t ≤ + (∑ j ∈ Finset.range J, blockWager B π w j X t) + + forcedWager (fun j => B (j + J)) π w X t + have hprefix : 0 ≤ ∑ j ∈ Finset.range J, blockWager B π w j X t := + Finset.sum_nonneg fun j _ => blockWager_nonneg B π w j X t + by_cases hf : BlockProductAnswer.forced B π (π.transcript X t) + · obtain ⟨j, hj⟩ := (forced_iff B π _).mp hf + change atTime B π j X t at hj + rw [forcedWager, ite_eq_left hf] + by_cases hlt : j < J + · have hterm : |w (π.transcript X t)| ≤ + ∑ k ∈ Finset.range J, blockWager B π w k X t := by + have hle := Finset.single_le_sum (fun k _ => blockWager_nonneg B π w k X t) + (Finset.mem_range.mpr hlt) + simpa only [blockWager, ite_eq_left hj] using hle + exact hterm.trans (le_add_of_nonneg_right + (forcedWager_nonneg (fun j => B (j + J)) π w X t)) + · have hge := Nat.le_of_not_gt hlt + have htail : BlockProductAnswer.forced (fun k => B (k + J)) π (π.transcript X t) := by + refine ⟨j - J, ?_⟩ + simpa only [atTime, atBlock, Nat.sub_add_cancel hge] using hj + rw [forcedWager, ite_eq_left htail] + exact le_add_of_nonneg_left hprefix + · rw [forcedWager, ite_eq_right hf] + exact add_nonneg hprefix (forcedWager_nonneg (fun j => B (j + J)) π w X t) + +/-- The concrete early/late estimates need only hold beyond any fixed block index. +The exceptional blocks are handled pathwise by freshness, without moment hypotheses. -/ +theorem ae_summable_forcedWager_tail (μ : Measure Cantor) (B : ℕ → AffineBlock) + (π : ScanRule) (w : List Bool → ℝ) (V : ℕ → ℕ) (J : ℕ) + (hlate : (∑' j, μ (lateEvent B π V (j + J))) < ∞) + (hearly : (∑' j, ∫⁻ X, ENNReal.ofReal (earlyWager B π w V (j + J) X) ∂μ) < ∞) : + ∀ᵐ X ∂μ, Summable (forcedWager B π w X) := by + have ht := ae_summable_forcedWager μ (fun j => B (j + J)) π w + (fun j => V (j + J)) hlate hearly + filter_upwards [ht] with X hX + exact summable_forcedWager_of_tail B π w X J hX + +/-- Summable numerical majorants for all sufficiently late blocks imply the actual +forced-wager conclusion. No estimate on the exceptional initial blocks is needed. -/ +theorem ae_summable_forcedWager_of_bounds (μ : Measure Cantor) (B : ℕ → AffineBlock) + (π : ScanRule) (w : List Bool → ℝ) (V : ℕ → ℕ) (J : ℕ) + (a b : ℕ → ℝ≥0∞) (ha : (∑' j, a j) < ∞) (hb : (∑' j, b j) < ∞) + (hlate : ∀ j, J ≤ j → μ (lateEvent B π V j) ≤ a j) + (hearly : ∀ j, J ≤ j → + (∫⁻ X, ENNReal.ofReal (earlyWager B π w V j X) ∂μ) ≤ b j) : + ∀ᵐ X ∂μ, Summable (forcedWager B π w X) := by + apply ae_summable_forcedWager_tail μ B π w V J + · calc + (∑' j, μ (lateEvent B π V (j + J))) ≤ ∑' j, a (j + J) := + tsum_le_tsum fun j => hlate (j + J) (Nat.le_add_left _ _) + _ ≤ ∑' j, a j := + tsum_comp_le_tsum_of_injective (fun _ _ h => Nat.add_right_cancel h) a + _ < ∞ := ha + · calc + (∑' j, ∫⁻ X, ENNReal.ofReal (earlyWager B π w V (j + J) X) ∂μ) ≤ + ∑' j, b (j + J) := + tsum_le_tsum fun j => hearly (j + J) (Nat.le_add_left _ _) + _ ≤ ∑' j, b j := + tsum_comp_le_tsum_of_injective (fun _ _ h => Nat.add_right_cancel h) b + _ < ∞ := hb + +end Klr.EarlyLateWagers diff --git a/LeanPool/KLRandomness/EffectiveNormalization.lean b/LeanPool/KLRandomness/EffectiveNormalization.lean new file mode 100644 index 0000000000..772d2fae3c --- /dev/null +++ b/LeanPool/KLRandomness/EffectiveNormalization.lean @@ -0,0 +1,329 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.ComputableRational +import Mathlib.Tactic.FieldSimp +import Mathlib.Tactic.Linarith +import Mathlib.Tactic.NormNum +import Mathlib.Tactic.Positivity +import Mathlib.Tactic.Ring + +/-! +# Effective rational capital with a positive reserve + +A computable real capital process is replaced by a computable rational one +whose value stays within `1/4` of `(d + 1) / 2` on every finite transcript. +The replacement approximates additive stakes at a summable error rate. It is +fair, starts at one, stays above `1/4`, and preserves unbounded capital. + +This supplies the effective reserve and rationalization step needed before +applying the pathwise normalization estimates in Lemma 2. +-/ + +@[expose] public section + +namespace Klr + +open RationalComputability + +private theorem foldl_take_succ {α β : Type*} (f : α → β → α) (s : α) + (v : List β) (n : ℕ) : + (v.take (n + 1)).foldl f s = + match v[n]? with + | none => (v.take n).foldl f s + | some b => f ((v.take n).foldl f s) b := by + induction v generalizing n s with + | nil => simp + | cons b v ih => + cases n with + | zero => simp + | succ n => simpa using ih (f s b) n + +/-- Total computability is closed under folding a finite list, even when the +step function is computable rather than primitive recursive. -/ +theorem computable_list_foldl {α β : Type*} [Primcodable α] [Primcodable β] + (f : α → β → α) (hf : Computable₂ f) (s : α) : + Computable (fun v : List β => v.foldl f s) := by + let step (v : List β) (p : ℕ × α) := + match v[p.1]? with + | none => p.2 + | some b => f p.2 b + have hstep : Computable₂ step := by + apply (Computable.option_casesOn + (Computable.list_getElem?.comp Computable.fst (Computable.fst.comp Computable.snd)) + (Computable.snd.comp Computable.snd) + (hf.comp (Computable.snd.comp (Computable.snd.comp Computable.fst)) + Computable.snd).to₂).of_eq + intro p + dsimp [step] + cases p.1[p.2.1]? <;> rfl + have hrec := Computable.nat_rec Computable.list_length (Computable.const s) hstep + apply hrec.of_eq + intro v + have haux : ∀ n, Nat.rec s (fun k acc => step v (k, acc)) n = (v.take n).foldl f s := by + intro n + induction n with + | zero => simp + | succ n ih => simp only [ih, foldl_take_succ, step] + simpa using haux v.length + +/-- The sign of the capital change for an observed Boolean answer. -/ +def answerSign (b : Bool) : ℚ := if b then 1 else -1 + +@[simp] theorem answerSign_false : answerSign false = -1 := rfl +@[simp] theorem answerSign_true : answerSign true = 1 := rfl + +@[simp] theorem abs_answerSign (b : Bool) : |answerSign b| = 1 := by + cases b <;> norm_num [answerSign] + +@[simp] theorem abs_cast_answerSign (b : Bool) : |(answerSign b : ℝ)| = 1 := by + cases b <;> norm_num [answerSign] + +@[simp] theorem cast_answerSign_sq (b : Bool) : (answerSign b : ℝ) ^ 2 = 1 := by + cases b <;> norm_num [answerSign] + +theorem primrec_answerSign : Primrec answerSign := Primrec.dom_bool _ + +/-- A uniformly computable rational approximation to a real capital process. -/ +structure CapitalApproximation (d : CapitalProcess) where + /-- Rational approximation to capital at a transcript and precision. -/ + value : List Bool → ℕ → ℚ + computable_value : Computable (fun p : List Bool × ℕ => value p.1 p.2) + error : ∀ v n, |(value v n : ℝ) - d.value v| ≤ (1 / 2 : ℝ) ^ n + +/-- Choose the rational approximation supplied by uniform capital computability. -/ +noncomputable def CapitalApproximation.ofComputable (d : CapitalProcess) + (hd : ComputableRealCapital d.value) : CapitalApproximation d := + let q := hd.choose + { value := q + computable_value := computable_rat_of_numDen hd.choose_spec.1 + error := hd.choose_spec.2 } + +namespace CapitalApproximation + +variable {d : CapitalProcess} + +/-- Approximate the additive stake of `(d + 1) / 2`, using two extra bits of +precision beyond the transcript length. -/ +def stake (q : CapitalApproximation d) (v : List Bool) : ℚ := + (q.value (v ++ [true]) (v.length + 2) - q.value (v ++ [false]) (v.length + 2)) / 4 + +/-- Advance the rational account by the approximate stake's signed return. -/ +def reserveStep (q : CapitalApproximation d) (p : List Bool × ℚ) (b : Bool) : + List Bool × ℚ := + (p.1 ++ [b], p.2 + answerSign b * q.stake p.1) + +/-- Transcript and capital obtained by applying all reserve-account updates. -/ +def reserveAccount (q : CapitalApproximation d) (v : List Bool) : List Bool × ℚ := + v.foldl q.reserveStep ([], 1) + +/-- Capital of the rational reserve account after the given transcript. -/ +def reserveValue (q : CapitalApproximation d) (v : List Bool) : ℚ := + (q.reserveAccount v).2 + +@[simp] theorem reserveAccount_snoc (q : CapitalApproximation d) (v : List Bool) (b : Bool) : + q.reserveAccount (v ++ [b]) = q.reserveStep (q.reserveAccount v) b := by + simp [reserveAccount, List.foldl_append] + +theorem reserveAccount_prefix (q : CapitalApproximation d) (v : List Bool) : + (q.reserveAccount v).1 = v := by + induction v using List.reverseRecOn with + | nil => rfl + | append_singleton v b ih => simp [reserveStep, ih] + +@[simp] theorem reserveValue_nil (q : CapitalApproximation d) : q.reserveValue [] = 1 := rfl + +theorem reserveValue_snoc (q : CapitalApproximation d) (v : List Bool) (b : Bool) : + q.reserveValue (v ++ [b]) = q.reserveValue v + answerSign b * q.stake v := by + simp [reserveValue, reserveStep, reserveAccount_prefix] + +/-- Average of the original real capital and the constant reserve account. -/ +noncomputable def target (d : CapitalProcess) (v : List Bool) : ℝ := (d.value v + 1) / 2 + +/-- Signed stake of the mixed account before rounding. -/ +noncomputable def targetStake (d : CapitalProcess) (v : List Bool) : ℝ := + (d.value (v ++ [true]) - d.value (v ++ [false])) / 4 + +theorem target_snoc (d : CapitalProcess) (v : List Bool) (b : Bool) : + target d (v ++ [b]) = target d v + (answerSign b : ℝ) * targetStake d v := by + have hf := d.fair v + cases b <;> simp [target, targetStake, answerSign] <;> linarith + +theorem stake_error (q : CapitalApproximation d) (v : List Bool) : + |(q.stake v : ℝ) - targetStake d v| ≤ (1 / 2 : ℝ) ^ (v.length + 3) := by + obtain ⟨hlt, hut⟩ := abs_le.mp (q.error (v ++ [true]) (v.length + 2)) + obtain ⟨hlf, huf⟩ := abs_le.mp (q.error (v ++ [false]) (v.length + 2)) + have hp : (1 / 2 : ℝ) ^ (v.length + 3) = (1 / 2 : ℝ) ^ (v.length + 2) / 2 := by + rw [show v.length + 3 = (v.length + 2) + 1 by omega, pow_succ] + ring + rw [hp, abs_le] + unfold stake targetStake + push_cast + constructor <;> linarith + +/-- The stronger geometric error estimate retains the unused error budget. -/ +theorem reserve_error_geometric (q : CapitalApproximation d) (v : List Bool) : + |(q.reserveValue v : ℝ) - target d v| ≤ + (1 / 4 : ℝ) * (1 - (1 / 2 : ℝ) ^ v.length) := by + induction v using List.reverseRecOn with + | nil => simp [target, d.initial] + | append_singleton v b ih => + have heq : (q.reserveValue (v ++ [b]) : ℝ) - target d (v ++ [b]) = + ((q.reserveValue v : ℝ) - target d v) + + (answerSign b : ℝ) * ((q.stake v : ℝ) - targetStake d v) := by + rw [reserveValue_snoc, target_snoc] + push_cast + ring + rw [heq] + calc + _ ≤ |(q.reserveValue v : ℝ) - target d v| + + |(answerSign b : ℝ) * ((q.stake v : ℝ) - targetStake d v)| := abs_add_le _ _ + _ = |(q.reserveValue v : ℝ) - target d v| + + |(q.stake v : ℝ) - targetStake d v| := by simp [abs_mul] + _ ≤ (1 / 4 : ℝ) * (1 - (1 / 2 : ℝ) ^ v.length) + + (1 / 2 : ℝ) ^ (v.length + 3) := add_le_add ih (q.stake_error v) + _ = _ := by + simp only [List.length_append, List.length_singleton, pow_add] + ring + +theorem reserve_error (q : CapitalApproximation d) (v : List Bool) : + |(q.reserveValue v : ℝ) - target d v| ≤ (1 / 4 : ℝ) := by + have hg := q.reserve_error_geometric v + have hp : 0 ≤ (1 / 2 : ℝ) ^ v.length := by positivity + linarith + +theorem reserve_lower (q : CapitalApproximation d) (v : List Bool) : + (1 / 4 : ℚ) ≤ q.reserveValue v := by + have h := (abs_le.mp (q.reserve_error v)).1 + have hd := d.nonneg v + have hr : (1 / 4 : ℝ) ≤ (q.reserveValue v : ℝ) := by + unfold target at h + linarith + apply (Rat.cast_le (K := ℝ)).mp + simpa only [Rat.cast_div, Rat.cast_one, Rat.cast_ofNat] using hr + +theorem reserve_fair (q : CapitalApproximation d) (v : List Bool) : + q.reserveValue (v ++ [false]) + q.reserveValue (v ++ [true]) = 2 * q.reserveValue v := by + simp only [reserveValue_snoc, answerSign_false, answerSign_true] + ring + +theorem computable_stake (q : CapitalApproximation d) : Computable q.stake := by + have hv (b : Bool) : Computable (fun v : List Bool => + q.value (v ++ [b]) (v.length + 2)) := by + have hb : Computable (fun v : List Bool => v ++ [b]) := + (Primrec.list_concat.comp Primrec.id (Primrec.const b)).to_comp + have hn : Computable (fun v : List Bool => v.length + 2) := + (Primrec.nat_add.comp Primrec.list_length (Primrec.const 2)).to_comp + have hc := Computable.comp q.computable_value (hb.pair hn) + exact hc.of_eq fun _ => rfl + have hc := primrec_rat_div.to_comp.comp + (primrec_rat_sub.to_comp.comp (hv true) (hv false)) (Computable.const 4) + exact hc.of_eq fun _ => rfl + +theorem computable_reserveStep (q : CapitalApproximation d) : Computable₂ q.reserveStep := by + have hc := (Computable.list_concat.comp (Computable.fst.comp Computable.fst) Computable.snd).pair + (primrec_rat_add.to_comp.comp (Computable.snd.comp Computable.fst) + (primrec_rat_mul.to_comp.comp (primrec_answerSign.to_comp.comp Computable.snd) + (q.computable_stake.comp (Computable.fst.comp Computable.fst)))) + exact hc.of_eq fun _ => rfl + +theorem computable_reserveValue (q : CapitalApproximation d) : Computable q.reserveValue := by + have hc := Computable.snd.comp + (computable_list_foldl q.reserveStep q.computable_reserveStep ([], 1)) + exact hc.of_eq fun _ => rfl + +end CapitalApproximation + +/-- A computable rational fair capital process with a fixed positive reserve. -/ +structure ReservedRationalCapital where + /-- Exact rational capital assigned to each transcript. -/ + value : List Bool → ℚ + initial : value [] = 1 + fair : ∀ v, value (v ++ [false]) + value (v ++ [true]) = 2 * value v + lower : ∀ v, (1 / 4 : ℚ) ≤ value v + computable_value : Computable value + +/-- The uniformly computable rational process with a positive reserve. -/ +def CapitalApproximation.reserve {d : CapitalProcess} (q : CapitalApproximation d) : + ReservedRationalCapital where + value := q.reserveValue + initial := q.reserveValue_nil + fair := q.reserve_fair + lower := q.reserve_lower + computable_value := q.computable_reserveValue + +namespace ReservedRationalCapital + +theorem positive (r : ReservedRationalCapital) (v : List Bool) : 0 < r.value v := by + have := r.lower v + linarith + +/-- Interpret reserved rational capital as a real fair capital process. -/ +def capital (r : ReservedRationalCapital) : CapitalProcess where + value v := (r.value v : ℝ) + initial := by simp [r.initial] + nonneg v := Rat.cast_nonneg.mpr (r.positive v).le + fair v := by exact_mod_cast r.fair v + +/-- Bet with reserved capital while following the given scan. -/ +def strategy (r : ReservedRationalCapital) (π : ScanRule) : BettingStrategy where + scan := π + capital := r.capital + computable_capital := computableRealCapital_of_rat r.computable_value + +/-- The fraction of current capital staked on the next answer. -/ +def wager (r : ReservedRationalCapital) (v : List Bool) : ℚ := + (r.value (v ++ [true]) - r.value (v ++ [false])) / (2 * r.value v) + +theorem update (r : ReservedRationalCapital) (v : List Bool) (b : Bool) : + r.value (v ++ [b]) = r.value v * (1 + answerSign b * r.wager v) := by + have hf := r.fair v + have hn := ne_of_gt (r.positive v) + unfold wager + cases b <;> simp only [answerSign_false, answerSign_true] <;> + field_simp <;> nlinarith + +theorem abs_wager_lt_one (r : ReservedRationalCapital) (v : List Bool) : + |r.wager v| < 1 := by + have hf := r.fair v + have ht := r.positive (v ++ [true]) + have hfalse := r.positive (v ++ [false]) + have hp := r.positive v + rw [wager, abs_lt] + constructor + · apply (lt_div_iff₀ (by positivity : 0 < 2 * r.value v)).mpr + linarith + · apply (div_lt_iff₀ (by positivity : 0 < 2 * r.value v)).mpr + linarith + +theorem computable_wager (r : ReservedRationalCapital) : Computable r.wager := by + have hv (b : Bool) : Computable (fun v : List Bool => r.value (v ++ [b])) := by + have hc := Computable.comp r.computable_value + (Computable.list_concat.comp Computable.id (Computable.const b)) + exact hc.of_eq fun _ => rfl + have hc := primrec_rat_div.to_comp.comp + (primrec_rat_sub.to_comp.comp (hv true) (hv false)) + (primrec_rat_mul.to_comp.comp (Computable.const 2) r.computable_value) + exact hc.of_eq fun _ => rfl + +end ReservedRationalCapital + +theorem CapitalApproximation.reserve_preserves_success (s : BettingStrategy) + (q : CapitalApproximation s.capital) {X : Cantor} (hs : s.Succeeds X) : + (q.reserve.strategy s.scan).Succeeds X := by + intro B + obtain ⟨n, hn⟩ := hs (2 * B) + refine ⟨n, ?_⟩ + change B < (q.reserveValue (s.scan.transcript X n) : ℝ) + have he := (abs_le.mp (q.reserve_error (s.scan.transcript X n))).1 + unfold CapitalApproximation.target at he + linarith + +end Klr diff --git a/LeanPool/KLRandomness/EffectiveNormalizationStrategy.lean b/LeanPool/KLRandomness/EffectiveNormalizationStrategy.lean new file mode 100644 index 0000000000..842be494f8 --- /dev/null +++ b/LeanPool/KLRandomness/EffectiveNormalizationStrategy.lean @@ -0,0 +1,347 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.EffectiveNormalization +public import LeanPool.KLRandomness.NormalizationSuccess +import Mathlib.Tactic.FieldSimp +import Mathlib.Tactic.Linarith +import Mathlib.Tactic.NormNum +import Mathlib.Tactic.Positivity +import Mathlib.Tactic.Ring + +/-! +# Effective strategy normalization + +This file completes Lemma 2 at the level of `BettingStrategy`. Every total +computable-real strategy is replaced, with the same scan, by a computable +rational strategy with positive capital, wager magnitude at most `1/2`, and +pathwise sum of squared wagers at most `1/2`. Success is preserved on every +input. The real-valued analytic result is applied only after proving that the +constructed strategy has exactly the required multiplicative capital. +-/ + +@[expose] public section + +namespace Klr + +open RationalComputability + +namespace ReservedRationalCapital + +/-- Transcript, accumulated squared source wagers, and normalized capital. -/ +abbrev NormalizationState := List Bool × (ℚ × ℚ) + +/-- Advance the transcript, squared-wager total and normalized capital by one answer. -/ +def normalizationStep (r : ReservedRationalCapital) (p : NormalizationState) (b : Bool) : + NormalizationState := + let f := r.wager p.1 + let h := f / (2 * (1 + p.2.1)) + (p.1 ++ [b], p.2.1 + f ^ 2, p.2.2 * (1 + answerSign b * h)) + +/-- The normalization state obtained by processing a finite transcript. -/ +def normalizationAccount (r : ReservedRationalCapital) (v : List Bool) : NormalizationState := + v.foldl r.normalizationStep ([], 0, 1) + +/-- The accumulated sum of squared original wager fractions. -/ +def variation (r : ReservedRationalCapital) (v : List Bool) : ℚ := + (r.normalizationAccount v).2.1 + +/-- The damped capital after processing the given transcript. -/ +def normalizedValue (r : ReservedRationalCapital) (v : List Bool) : ℚ := + (r.normalizationAccount v).2.2 + +/-- The original wager fraction damped by the accumulated squared wagers. -/ +def normalizedFraction (r : ReservedRationalCapital) (v : List Bool) : ℚ := + r.wager v / (2 * (1 + r.variation v)) + +@[simp] theorem normalizationAccount_snoc (r : ReservedRationalCapital) + (v : List Bool) (b : Bool) : + r.normalizationAccount (v ++ [b]) = r.normalizationStep (r.normalizationAccount v) b := by + simp [normalizationAccount, List.foldl_append] + +theorem normalizationAccount_prefix (r : ReservedRationalCapital) (v : List Bool) : + (r.normalizationAccount v).1 = v := by + induction v using List.reverseRecOn with + | nil => rfl + | append_singleton v b ih => simp [normalizationStep, ih] + +@[simp] theorem variation_nil (r : ReservedRationalCapital) : r.variation [] = 0 := rfl + +theorem variation_snoc (r : ReservedRationalCapital) (v : List Bool) (b : Bool) : + r.variation (v ++ [b]) = r.variation v + (r.wager v) ^ 2 := by + simp [variation, normalizationStep, normalizationAccount_prefix] + +theorem variation_nonneg (r : ReservedRationalCapital) (v : List Bool) : 0 ≤ r.variation v := by + induction v using List.reverseRecOn with + | nil => simp + | append_singleton v b ih => rw [variation_snoc]; positivity + +theorem normalizedFraction_abs_le_half (r : ReservedRationalCapital) (v : List Bool) : + |r.normalizedFraction v| ≤ (1 / 2 : ℚ) := by + have hq := r.variation_nonneg v + have hf := (r.abs_wager_lt_one v).le + have hd : 0 < 2 * (1 + r.variation v) := by positivity + rw [normalizedFraction, abs_div, abs_of_pos hd] + apply (div_le_iff₀ hd).mpr + linarith + +@[simp] theorem normalizedValue_nil (r : ReservedRationalCapital) : r.normalizedValue [] = 1 := rfl + +theorem normalizedValue_snoc (r : ReservedRationalCapital) (v : List Bool) (b : Bool) : + r.normalizedValue (v ++ [b]) = + r.normalizedValue v * (1 + answerSign b * r.normalizedFraction v) := by + simp [normalizedValue, normalizationStep, normalizedFraction, variation, + normalizationAccount_prefix] + +theorem normalizedValue_positive (r : ReservedRationalCapital) (v : List Bool) : + 0 < r.normalizedValue v := by + induction v using List.reverseRecOn with + | nil => norm_num + | append_singleton v b ih => + rw [normalizedValue_snoc] + apply mul_pos ih + obtain ⟨hl, hu⟩ := abs_le.mp (r.normalizedFraction_abs_le_half v) + cases b <;> simp only [answerSign_false, answerSign_true] <;> linarith + +theorem normalizedValue_fair (r : ReservedRationalCapital) (v : List Bool) : + r.normalizedValue (v ++ [false]) + r.normalizedValue (v ++ [true]) = + 2 * r.normalizedValue v := by + simp only [normalizedValue_snoc, answerSign_false, answerSign_true] + ring + +theorem computable_normalizationStep (r : ReservedRationalCapital) : + Computable₂ r.normalizationStep := by + have hf : Computable (fun p : NormalizationState × Bool => r.wager p.1.1) := by + have hp : Computable (fun p : NormalizationState × Bool => p.1.1) := + Computable.fst.comp Computable.fst + have hc := r.computable_wager.comp hp + exact hc.of_eq fun _ => rfl + have hq : Computable (fun p : NormalizationState × Bool => p.1.2.1) := + Computable.fst.comp (Computable.snd.comp Computable.fst) + have hc : Computable (fun p : NormalizationState × Bool => p.1.2.2) := + Computable.snd.comp (Computable.snd.comp Computable.fst) + have hh : Computable (fun p : NormalizationState × Bool => + r.wager p.1.1 / (2 * (1 + p.1.2.1))) := by + have hc := primrec_rat_div.to_comp.comp hf + (primrec_rat_mul.to_comp.comp (Computable.const 2) + (primrec_rat_add.to_comp.comp (Computable.const 1) hq)) + exact hc.of_eq fun _ => rfl + have hqq : Computable (fun p : NormalizationState × Bool => p.1.2.1 + (r.wager p.1.1)^2) := by + have hc := primrec_rat_add.to_comp.comp hq + (primrec_rat_mul.to_comp.comp hf hf) + exact hc.of_eq fun _ => by simp only [pow_two] + have hc := (Computable.list_concat.comp (Computable.fst.comp Computable.fst) Computable.snd).pair + (hqq.pair (primrec_rat_mul.to_comp.comp hc + (primrec_rat_add.to_comp.comp (Computable.const 1) + (primrec_rat_mul.to_comp.comp (primrec_answerSign.to_comp.comp Computable.snd) hh)))) + exact hc.of_eq fun _ => rfl + +theorem computable_normalizationAccount (r : ReservedRationalCapital) : + Computable r.normalizationAccount := by + have hc := computable_list_foldl r.normalizationStep r.computable_normalizationStep ([], 0, 1) + exact hc.of_eq fun _ => rfl + +theorem computable_normalizedValue (r : ReservedRationalCapital) : + Computable r.normalizedValue := by + have hc := Computable.snd.comp (Computable.snd.comp r.computable_normalizationAccount) + exact hc.of_eq fun _ => rfl + +/-- The normalized capital as a real fair process. -/ +def normalizedCapital (r : ReservedRationalCapital) : CapitalProcess where + value v := (r.normalizedValue v : ℝ) + initial := by simp + nonneg v := Rat.cast_nonneg.mpr (r.normalizedValue_positive v).le + fair v := by exact_mod_cast r.normalizedValue_fair v + +/-- The normalized process paired with the original adaptive scan. -/ +def normalizedStrategy (r : ReservedRationalCapital) (π : ScanRule) : BettingStrategy where + scan := π + capital := r.normalizedCapital + computable_capital := computableRealCapital_of_rat r.computable_normalizedValue + +theorem normalizedCapital_positive (r : ReservedRationalCapital) (v : List Bool) : + 0 < r.normalizedCapital.value v := Rat.cast_pos.mpr (r.normalizedValue_positive v) + +theorem normalizedCapital_wager (r : ReservedRationalCapital) (v : List Bool) : + r.normalizedCapital.wager v = (r.normalizedFraction v : ℝ) := by + have hn : (r.normalizedValue v : ℝ) ≠ 0 := ne_of_gt (r.normalizedCapital_positive v) + change ((r.normalizedValue (v ++ [true]) : ℝ) - + (r.normalizedValue (v ++ [false]) : ℝ)) / (2 * (r.normalizedValue v : ℝ)) = _ + rw [normalizedValue_snoc, normalizedValue_snoc] + simp only [answerSign_true, answerSign_false] + push_cast + field_simp + ring + +theorem normalizedCapital_wager_abs_le_half (r : ReservedRationalCapital) (v : List Bool) : + |r.normalizedCapital.wager v| ≤ (1 / 2 : ℝ) := by + rw [normalizedCapital_wager] + have h := (Rat.cast_le (K := ℝ)).mpr (r.normalizedFraction_abs_le_half v) + simpa only [Rat.cast_abs, Rat.cast_div, Rat.cast_one, Rat.cast_ofNat] using h + +/-- Original wager fraction at one time along the run on an input. -/ +noncomputable def pathWager (r : ReservedRationalCapital) (π : ScanRule) (X : Cantor) (n : ℕ) : ℝ := + (r.wager (π.transcript X n) : ℝ) + +/-- Wager fraction multiplied by the sign of the next observed answer. -/ +noncomputable def pathReturn (r : ReservedRationalCapital) + (π : ScanRule) (X : Cantor) (n : ℕ) : ℝ := + (answerSign (X (π.query (π.transcript X n))) : ℝ) * r.pathWager π X n + +theorem pathWager_abs_lt_one (r : ReservedRationalCapital) (π : ScanRule) (X : Cantor) (n : ℕ) : + |r.pathWager π X n| < 1 := by + have h := (Rat.cast_lt (K := ℝ)).mpr (r.abs_wager_lt_one (π.transcript X n)) + simpa only [Rat.cast_abs, Rat.cast_one, pathWager] using h + +theorem pathReturn_abs_lt_one (r : ReservedRationalCapital) (π : ScanRule) (X : Cantor) (n : ℕ) : + |r.pathReturn π X n| < 1 := by + simpa [pathReturn, abs_mul] using r.pathWager_abs_lt_one π X n + +theorem pathReturn_sq (r : ReservedRationalCapital) (π : ScanRule) (X : Cantor) (n : ℕ) : + (r.pathReturn π X n)^2 = (r.pathWager π X n)^2 := by + simp [pathReturn, mul_pow] + +theorem variation_transcript (r : ReservedRationalCapital) (π : ScanRule) (X : Cantor) (n : ℕ) : + (r.variation (π.transcript X n) : ℝ) = quadraticVariation (r.pathWager π X) n := by + induction n with + | zero => simp + | succ n ih => + rw [ScanRule.transcript_succ, variation_snoc, quadraticVariation_succ] + push_cast + rw [ih] + rfl + +theorem variation_return (r : ReservedRationalCapital) (π : ScanRule) (X : Cantor) (n : ℕ) : + (r.variation (π.transcript X n) : ℝ) = quadraticVariation (r.pathReturn π X) n := by + rw [variation_transcript] + simp only [quadraticVariation, pathReturn_sq] + +theorem normalizedFraction_transcript (r : ReservedRationalCapital) + (π : ScanRule) (X : Cantor) (n : ℕ) : + (r.normalizedFraction (π.transcript X n) : ℝ) = normalizedWager (r.pathWager π X) n := by + unfold normalizedFraction normalizedWager + push_cast + rw [variation_transcript] + rfl + +theorem normalizedReturn_transcript (r : ReservedRationalCapital) + (π : ScanRule) (X : Cantor) (n : ℕ) : + (answerSign (X (π.query (π.transcript X n))) : ℝ) * + (r.normalizedFraction (π.transcript X n) : ℝ) = + normalizedWager (r.pathReturn π X) n := by + unfold normalizedFraction normalizedWager + push_cast + rw [variation_return] + unfold pathReturn pathWager + ring + +theorem reserve_product (r : ReservedRationalCapital) (π : ScanRule) (X : Cantor) (n : ℕ) : + multiplicativeCapital (r.pathReturn π X) n = (r.value (π.transcript X n) : ℝ) := by + induction n with + | zero => simp [r.initial] + | succ n ih => + rw [multiplicativeCapital_succ, ih, ScanRule.transcript_succ, r.update] + push_cast + rfl + +theorem normalized_product (r : ReservedRationalCapital) (π : ScanRule) (X : Cantor) (n : ℕ) : + multiplicativeCapital (normalizedWager (r.pathReturn π X)) n = + (r.normalizedValue (π.transcript X n) : ℝ) := by + induction n with + | zero => simp + | succ n ih => + rw [multiplicativeCapital_succ, ih, ScanRule.transcript_succ, normalizedValue_snoc] + push_cast + rw [normalizedReturn_transcript] + +theorem normalized_wagers_summable (r : ReservedRationalCapital) (π : ScanRule) (X : Cantor) : + Summable (fun n => (r.normalizedCapital.wager (π.transcript X n))^2) := by + simp only [normalizedCapital_wager, normalizedFraction_transcript] + exact summable_normalizedWager_sq _ (fun n => (r.pathWager_abs_lt_one π X n).le) + +theorem normalized_wagers_sum_le_half (r : ReservedRationalCapital) + (π : ScanRule) (X : Cantor) (N : ℕ) : + (∑ n ∈ Finset.range N, (r.normalizedCapital.wager (π.transcript X n))^2) ≤ + (1 / 2 : ℝ) := by + simp only [normalizedCapital_wager, normalizedFraction_transcript] + exact sum_normalizedWager_sq_le_half _ + (fun n => (sq_le_one_iff_abs_le_one _).mpr (r.pathWager_abs_lt_one π X n).le) N + +theorem normalized_wagers_tsum_le_half (r : ReservedRationalCapital) (π : ScanRule) (X : Cantor) : + (∑' n, (r.normalizedCapital.wager (π.transcript X n))^2) ≤ (1 / 2 : ℝ) := by + simp only [normalizedCapital_wager, normalizedFraction_transcript] + exact tsum_normalizedWager_sq_le_half _ (fun n => (r.pathWager_abs_lt_one π X n).le) + +theorem normalization_preserves_success (r : ReservedRationalCapital) (π : ScanRule) + {X : Cantor} (hs : (r.strategy π).Succeeds X) : (r.normalizedStrategy π).Succeeds X := by + have hunbounded : ¬ BddAbove (Set.range (multiplicativeCapital (r.pathReturn π X))) := by + rintro ⟨B, hB⟩ + obtain ⟨n, hn⟩ := hs B + have hb := hB (Set.mem_range_self n) + rw [reserve_product] at hb + exact (not_lt_of_ge hb) hn + have hreserve : ∀ n, (1 / 4 : ℝ) ≤ multiplicativeCapital (r.pathReturn π X) n := by + intro n + rw [reserve_product] + have h := (Rat.cast_le (K := ℝ)).mpr (r.lower (π.transcript X n)) + simpa only [Rat.cast_div, Rat.cast_one, Rat.cast_ofNat] using h + have hnorm := normalization_preserves_unbounded_capital (r.pathReturn π X) (1 / 4) + (r.pathReturn_abs_lt_one π X) (by norm_num) hreserve hunbounded + intro B + by_contra! h + apply hnorm + refine ⟨B, ?_⟩ + rintro _ ⟨n, rfl⟩ + rw [normalized_product] + exact h n + +end ReservedRationalCapital + +/-- The effective Lemma 2 transformation. The chosen approximation is a +uniform computable witness from the input strategy's existing interface. -/ +noncomputable def BettingStrategy.normalize (s : BettingStrategy) : BettingStrategy := + (CapitalApproximation.ofComputable s.capital s.computable_capital).reserve.normalizedStrategy + s.scan + +@[simp] theorem BettingStrategy.normalize_scan (s : BettingStrategy) : + s.normalize.scan = s.scan := rfl + +theorem BettingStrategy.normalize_positive (s : BettingStrategy) (v : List Bool) : + 0 < s.normalize.capital.value v := + ReservedRationalCapital.normalizedCapital_positive _ v + +theorem BettingStrategy.normalize_wager_abs_le_half (s : BettingStrategy) (v : List Bool) : + |s.normalize.capital.wager v| ≤ (1 / 2 : ℝ) := + ReservedRationalCapital.normalizedCapital_wager_abs_le_half _ v + +theorem BettingStrategy.normalize_wagers_summable (s : BettingStrategy) (X : Cantor) : + Summable (fun n => (s.normalize.capital.wager (s.normalize.scan.transcript X n))^2) := + ReservedRationalCapital.normalized_wagers_summable _ s.scan X + +theorem BettingStrategy.normalize_wagers_sum_le_half (s : BettingStrategy) (X : Cantor) (N : ℕ) : + (∑ n ∈ Finset.range N, + (s.normalize.capital.wager (s.normalize.scan.transcript X n))^2) ≤ (1 / 2 : ℝ) := + ReservedRationalCapital.normalized_wagers_sum_le_half _ s.scan X N + +theorem BettingStrategy.normalize_wagers_tsum_le_half (s : BettingStrategy) (X : Cantor) : + (∑' n, (s.normalize.capital.wager (s.normalize.scan.transcript X n))^2) ≤ (1 / 2 : ℝ) := + ReservedRationalCapital.normalized_wagers_tsum_le_half _ s.scan X + +theorem BettingStrategy.normalize_preserves_success (s : BettingStrategy) {X : Cantor} + (hs : s.Succeeds X) : s.normalize.Succeeds X := + ReservedRationalCapital.normalization_preserves_success _ s.scan + ((CapitalApproximation.ofComputable s.capital s.computable_capital).reserve_preserves_success + s hs) + +theorem BettingStrategy.normalize_rational (s : BettingStrategy) : + ∃ d : List Bool → ℚ, Computable d ∧ ∀ v, s.normalize.capital.value v = (d v : ℝ) := + ⟨_, ReservedRationalCapital.computable_normalizedValue _, fun _ => rfl⟩ + +end Klr diff --git a/LeanPool/KLRandomness/EffectiveOpen.lean b/LeanPool/KLRandomness/EffectiveOpen.lean new file mode 100644 index 0000000000..91d4ff72eb --- /dev/null +++ b/LeanPool/KLRandomness/EffectiveOpen.lean @@ -0,0 +1,107 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.Cantor +public import Mathlib.Computability.RE + +/-! +# Effectively open classes + +The effectiveness condition is Mathlib's `REPred`, i.e. the domain of a partial +recursive function. A single program on pairs `(n,s)` gives a uniformly +effectively open sequence; separate programs with no uniformity are insufficient. +-/ + +@[expose] public section + +namespace Klr + +open MeasureTheory + +/-- The open class generated by a collection of finite binary strings. -/ +def cylinderUnion (W : List Bool → Prop) : Set Cantor := + {X | ∃ s, W s ∧ X ∈ cylinder s} + +theorem cylinderUnion_eq_iUnion (W : List Bool → Prop) : + cylinderUnion W = ⋃ s, ⋃ (_ : W s), cylinder s := by + ext X + simp [cylinderUnion] + +theorem isOpen_cylinderUnion (W : List Bool → Prop) : IsOpen (cylinderUnion W) := by + rw [cylinderUnion_eq_iUnion] + exact isOpen_iUnion fun s => isOpen_iUnion fun _ => isOpen_cylinder s + +theorem measurableSet_cylinderUnion (W : List Bool → Prop) : + MeasurableSet (cylinderUnion W) := by + rw [cylinderUnion_eq_iUnion] + exact MeasurableSet.iUnion fun s => MeasurableSet.iUnion fun _ => measurableSet_cylinder s + +/-- A `Σ⁰₁` class: a union of cylinders from a computably enumerable set of strings. -/ +def IsEffectivelyOpen (U : Set Cantor) : Prop := + ∃ W : List Bool → Prop, REPred W ∧ U = cylinderUnion W + +theorem IsEffectivelyOpen.isOpen {U : Set Cantor} (hU : IsEffectivelyOpen U) : + IsOpen U := by + obtain ⟨W, _, rfl⟩ := hU + exact isOpen_cylinderUnion W + +theorem IsEffectivelyOpen.measurableSet {U : Set Cantor} (hU : IsEffectivelyOpen U) : + MeasurableSet U := by + obtain ⟨W, _, rfl⟩ := hU + exact measurableSet_cylinderUnion W + +/-- One c.e. predicate enumerates the cylinders of every level. -/ +def IsUniformlyEffectivelyOpen (U : ℕ → Set Cantor) : Prop := + ∃ W : ℕ × List Bool → Prop, REPred W ∧ + ∀ n, U n = cylinderUnion (fun s => W (n, s)) + +theorem IsUniformlyEffectivelyOpen.level {U : ℕ → Set Cantor} + (hU : IsUniformlyEffectivelyOpen U) (n : ℕ) : IsEffectivelyOpen (U n) := by + obtain ⟨W, hW, hU⟩ := hU + exact ⟨fun s => W (n, s), hW.comp ((Computable.const n).pair Computable.id), hU n⟩ + +/-- The c.e. predicate recognized by a program, using the standard encoding. -/ +def programAccepts {α : Type*} [Primcodable α] (c : Nat.Partrec.Code) (a : α) : Prop := + (c.eval (Encodable.encode a)).Dom + +theorem programAccepts_re {α : Type*} [Primcodable α] (c : Nat.Partrec.Code) : + REPred (programAccepts (α := α) c) := + (Nat.Partrec.Code.eval_part.comp (Computable.const c) Computable.encode).dom_re + +/-- Every c.e. predicate has a program recognizing exactly its members. -/ +theorem exists_programAccepts {α : Type*} [Primcodable α] {W : α → Prop} + (hW : REPred W) : ∃ c : Nat.Partrec.Code, ∀ a, programAccepts c a ↔ W a := by + obtain ⟨c, hc⟩ := Nat.Partrec.Code.exists_code.mp hW + refine ⟨c, fun a => ?_⟩ + simp [programAccepts, hc, Part.assert] + +/-- The uniformly effectively open sequence enumerated by a single program. -/ +def programOpen (c : Nat.Partrec.Code) (n : ℕ) : Set Cantor := + cylinderUnion (fun s => programAccepts c (n, s)) + +theorem programOpen_uniform (c : Nat.Partrec.Code) : + IsUniformlyEffectivelyOpen (programOpen c) := + ⟨programAccepts c, programAccepts_re c, fun _ => rfl⟩ + +/-- Program codes represent every uniformly c.e. family, not just a selected subclass. -/ +theorem isUniformlyEffectivelyOpen_iff_exists_program (U : ℕ → Set Cantor) : + IsUniformlyEffectivelyOpen U ↔ + ∃ c : Nat.Partrec.Code, ∀ n, U n = programOpen c n := by + constructor + · rintro ⟨W, hW, hU⟩ + obtain ⟨c, hc⟩ := exists_programAccepts hW + refine ⟨c, fun n => ?_⟩ + rw [hU n] + ext X + simp only [programOpen, cylinderUnion, Set.mem_ofPred_eq, hc] + · rintro ⟨c, hU⟩ + exact ⟨programAccepts c, programAccepts_re c, hU⟩ + +end Klr diff --git a/LeanPool/KLRandomness/EffectiveScan.lean b/LeanPool/KLRandomness/EffectiveScan.lean new file mode 100644 index 0000000000..f8995154f5 --- /dev/null +++ b/LeanPool/KLRandomness/EffectiveScan.lean @@ -0,0 +1,161 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.ComputableNonrandom +public import LeanPool.KLRandomness.EffectiveSearch +public import LeanPool.KLRandomness.ScanMeasure + +/-! +# Effective open events defined by finite adaptive transcripts + +A computable condition on a finite transcript gives a uniformly effectively +open input event. Finite input strings are accepted when they contain every +queried coordinate and agree with all the transcript's prescribed answers. +-/ + +@[expose] public section + +namespace Klr.EffectiveScan + +/-- Bounded conjunction, retaining the computation parameter outside the loop. -/ +def boundedAll (p : ℕ → Bool) : ℕ → Bool + | 0 => true + | n + 1 => boundedAll p n && p n + +theorem boundedAll_eq_true (p : ℕ → Bool) (n : ℕ) : + boundedAll p n = true ↔ ∀ i < n, p i = true := by + induction n with + | zero => simp [boundedAll] + | succ n ih => + rw [boundedAll, Bool.and_eq_true, ih] + constructor + · rintro ⟨h, hn⟩ i hi + rcases lt_or_eq_of_le (Nat.le_of_lt_succ hi) with hlt | rfl + · exact h i hlt + · exact hn + · intro h + exact ⟨fun i hi => h i (by omega), h n (by omega)⟩ + +theorem computable_boundedAll {α : Type*} [Primcodable α] {p : α → ℕ → Bool} + (hp : Computable₂ p) : Computable (fun a : α × ℕ => boundedAll (p a.1) a.2) := by + have hs : Computable₂ (fun (a : α × ℕ) (b : ℕ × Bool) => b.2 && p a.1 b.1) := + (Primrec.and.to_comp.comp (Computable.snd.comp Computable.snd) + (hp.comp (Computable.fst.comp Computable.fst) + (Computable.fst.comp Computable.snd))).to₂ + apply (Computable.nat_rec Computable.snd (Computable.const true) hs).of_eq + intro a + induction a.2 with + | zero => rfl + | succ n ih => simpa only [boundedAll, Nat.rec_add_one] using congrArg (· && p a.1 n) ih + +/-- A finite input prefix determines every queried bit of a finite transcript. -/ +def agrees (π : ScanRule) (v s : List Bool) : Bool := + boundedAll (fun i => decide (π.query (v.take i) < s.length) && + decide (s.getD (π.query (v.take i)) false = v.getD i false)) v.length + +theorem agrees_eq_true (π : ScanRule) (v s : List Bool) : + agrees π v s = true ↔ ∀ i < v.length, + π.query (v.take i) < s.length ∧ + s.getD (π.query (v.take i)) false = v.getD i false := by + simp only [agrees, boundedAll_eq_true, Bool.and_eq_true, decide_eq_true_eq] + +theorem computable_agrees (π : ScanRule) : + Computable (fun p : List Bool × List Bool => agrees π p.1 p.2) := by + have hq : Computable (fun p : (List Bool × List Bool) × ℕ => + π.query (p.1.1.take p.2)) := + π.computable_query.comp (Primrec.list_take.to_comp.comp Computable.snd + (Computable.fst.comp Computable.fst)) + have hlen : Computable (fun p : (List Bool × List Bool) × ℕ => p.1.2.length) := + Computable.list_length.comp (Computable.snd.comp Computable.fst) + have hs : Computable (fun p : (List Bool × List Bool) × ℕ => + p.1.2.getD (π.query (p.1.1.take p.2)) false) := + (Primrec.list_getD false).to_comp.comp (Computable.snd.comp Computable.fst) hq + have hv : Computable (fun p : (List Bool × List Bool) × ℕ => + p.1.1.getD p.2 false) := + (Primrec.list_getD false).to_comp.comp (Computable.fst.comp Computable.fst) Computable.snd + have hp : Computable₂ (fun p : List Bool × List Bool => fun i => + decide (π.query (p.1.take i) < p.2.length) && + decide (p.2.getD (π.query (p.1.take i)) false = p.1.getD i false)) := by + have hc := Primrec.and.to_comp.comp + (Primrec.nat_lt.decide.to_comp.comp hq hlen) + (Primrec.eq.decide.to_comp.comp hs hv) + exact hc.of_eq fun _ => rfl + have hc := (computable_boundedAll hp).comp + (Computable.id.pair (Computable.list_length.comp Computable.fst)) + exact hc.of_eq fun _ => rfl + +theorem transcript_of_agrees (π : ScanRule) (v s : List Bool) (h : agrees π v s = true) + {X : Cantor} (hX : X ∈ cylinder s) : π.transcript X v.length = v := by + apply (π.transcript_eq_iff X v).mpr + intro i hi + obtain ⟨hq, hb⟩ := (agrees_eq_true π v s).mp h i hi + exact (hX _ hq).trans hb + +theorem exists_prefix_agrees (π : ScanRule) (X : Cantor) (v : List Bool) + (hv : π.transcript X v.length = v) : + ∃ s : List Bool, X ∈ cylinder s ∧ agrees π v s = true := by + classical + let N := (Finset.univ : Finset (Fin v.length)).sup + (fun i => π.query (v.take i.val)) + 1 + refine ⟨ScanRule.inputPrefix X N, ScanRule.mem_cylinder_inputPrefix X N, ?_⟩ + rw [agrees_eq_true] + intro i hi + have hq : π.query (v.take i) < N := by + exact Nat.lt_succ_of_le (Finset.le_sup (f := fun j : Fin v.length => + π.query (v.take j.val)) (Finset.mem_univ ⟨i, hi⟩)) + constructor + · simpa only [ScanRule.length_inputPrefix] using hq + · rw [ScanRule.getD_inputPrefix X hq] + exact (π.transcript_eq_iff X v).mp hv i hi + +/-- Input events specified by a condition on some finite adaptive transcript. -/ +def openEvent (π : ScanRule) (R : ℕ × List Bool → Prop) (m : ℕ) : Set Cantor := + {X | ∃ v, R (m, v) ∧ π.transcript X v.length = v} + +/-- A finite witness checks the transcript condition and all queried input bits. -/ +def accepts (π : ScanRule) (r : ℕ × List Bool → Bool) + (p : (ℕ × List Bool) × List Bool) : Bool := + r (p.1.1, p.2) && agrees π p.2 p.1.2 + +theorem computable_accepts (π : ScanRule) {r : ℕ × List Bool → Bool} + (hr : Computable r) : Computable (accepts π r) := by + have hleft : Computable (fun p : (ℕ × List Bool) × List Bool => (p.1.1, p.2)) := + (Computable.fst.comp Computable.fst).pair Computable.snd + have hright : Computable (fun p : (ℕ × List Bool) × List Bool => (p.2, p.1.2)) := + Computable.snd.pair (Computable.snd.comp Computable.fst) + have hR := hr.comp hleft + have hA := (computable_agrees π).comp hright + have hc := Primrec.and.to_comp.comp hR hA + exact hc.of_eq fun _ => rfl + +theorem computablePred_accepts (π : ScanRule) {r : ℕ × List Bool → Bool} + (hr : Computable r) : ComputablePred (fun p => accepts π r p = true) := + ComputablePred.computable_iff.mpr ⟨accepts π r, computable_accepts π hr, rfl⟩ + +/-- Uniformly computable transcript conditions yield uniformly effectively open input events. -/ +theorem openEvent_uniform (π : ScanRule) {R : ℕ × List Bool → Prop} + (hR : ComputablePred R) : IsUniformlyEffectivelyOpen (openEvent π R) := by + classical + obtain ⟨r, hr, rfl⟩ := ComputablePred.computable_iff.mp hR + refine ⟨fun p => ∃ v, accepts π r (p, v) = true, + rePred_exists (computablePred_accepts π hr).to_re, fun m => ?_⟩ + ext X + constructor + · rintro ⟨v, hR, hv⟩ + obtain ⟨s, hXs, hs⟩ := exists_prefix_agrees π X v hv + refine ⟨s, ⟨v, ?_⟩, hXs⟩ + simpa only [accepts, Bool.and_eq_true] using And.intro hR hs + · rintro ⟨s, ⟨v, h⟩, hXs⟩ + have hvhs : r (m, v) = true ∧ agrees π v s = true := by + simpa only [accepts, Bool.and_eq_true] using h + obtain ⟨hv, hs⟩ := hvhs + exact ⟨v, hv, transcript_of_agrees π v s hs hXs⟩ + +end Klr.EffectiveScan diff --git a/LeanPool/KLRandomness/EffectiveSearch.lean b/LeanPool/KLRandomness/EffectiveSearch.lean new file mode 100644 index 0000000000..a0f8c8adc8 --- /dev/null +++ b/LeanPool/KLRandomness/EffectiveSearch.lean @@ -0,0 +1,55 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.EffectiveOpen + +/-! +# Effective existential search + +A computably enumerable relation remains computably enumerable after an +existential quantifier over any primitively encodable type. The proof dovetails +over both possible witnesses and bounded computation stages. In particular, it +does not wait forever for an unsuccessful candidate witness. +-/ + +@[expose] public section + +namespace Klr + +/-- Existential projection preserves computable enumerability. -/ +theorem rePred_exists {α β : Type*} [Primcodable α] [Primcodable β] + {W : α × β → Prop} (hW : REPred W) : REPred (fun a => ∃ b, W (a, b)) := by + obtain ⟨c, hc⟩ := exists_programAccepts hW + let search (a : α) (k : ℕ) : Option ℕ := + (Encodable.decode (α := β × ℕ) k).bind fun bt => + Nat.Partrec.Code.evaln bt.2 c (Encodable.encode (a, bt.1)) + have hbounded : Computable₂ (fun (p : α × ℕ) (bt : β × ℕ) => + Nat.Partrec.Code.evaln bt.2 c (Encodable.encode (p.1, bt.1))) := + (Nat.Partrec.Code.primrec_evaln.to_comp.comp + (((Computable.snd.comp Computable.snd).pair (Computable.const c)).pair + (Computable.encode.comp ((Computable.fst.comp Computable.fst).pair + (Computable.fst.comp Computable.snd))))).to₂ + have hsearch : Computable₂ search := + (Computable.option_bind (Computable.decode.comp Computable.snd) hbounded).to₂ + apply (Partrec.rfindOpt hsearch).dom_re.of_eq + intro a + rw [Nat.rfindOpt_dom] + constructor + · rintro ⟨k, x, hx⟩ + obtain ⟨⟨b, t⟩, _, hbt⟩ := Option.mem_bind_iff.mp hx + refine ⟨b, (hc (a, b)).mp ?_⟩ + exact Part.dom_iff_mem.mpr ⟨x, Nat.Partrec.Code.evaln_sound hbt⟩ + · rintro ⟨b, hb⟩ + obtain ⟨x, hx⟩ := Part.dom_iff_mem.mp ((hc (a, b)).mpr hb) + obtain ⟨t, ht⟩ := Nat.Partrec.Code.evaln_complete.mp hx + refine ⟨Encodable.encode (b, t), x, ?_⟩ + simpa [search] using ht + +end Klr diff --git a/LeanPool/KLRandomness/FairForced.lean b/LeanPool/KLRandomness/FairForced.lean new file mode 100644 index 0000000000..4f52b4530e --- /dev/null +++ b/LeanPool/KLRandomness/FairForced.lean @@ -0,0 +1,374 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.MaximalInequality +public import LeanPool.KLRandomness.EffectiveNormalization +public import Mathlib.Analysis.SpecificLimits.Basic +public import Mathlib.Analysis.SpecialFunctions.Exp +import Mathlib.Tactic.GCongr +import Mathlib.Tactic.Linarith +import Mathlib.Tactic.NormNum +import Mathlib.Tactic.Ring + +/-! +# Bounded capital from fair steps and summable forced wagers + +This is the probabilistic conclusion needed in Section 6, with its two genuine +application obligations stated explicitly: selected finite histories have fair +next-answer probabilities, and the absolute wagers at all other steps are +summable almost surely. A weighted-cylinder maximal inequality bounds the +fair-only product. The remaining product is bounded by the exponential of its +absolute-wager sum. No martingale convergence assumption is used. +-/ + +@[expose] public section + +namespace Klr.FairForced + +open MeasureTheory +open scoped ENNReal + +/-- The set of inputs with the specified observed transcript. -/ +def event (π : ScanRule) (v : List Bool) : Set Cantor := + {X | π.transcript X v.length = v} + +@[simp] theorem event_nil (π : ScanRule) : event π [] = Set.univ := by + ext X + simp [event] + +theorem measurableSet_event (π : ScanRule) (v : List Bool) : MeasurableSet (event π v) := + π.measurableSet_transcript v + +theorem event_snoc (π : ScanRule) (v : List Bool) (b : Bool) : + event π (v ++ [b]) = event π v ∩ {X | X (π.query v) = b} := by + ext X + constructor + · intro h + change π.transcript X (v ++ [b]).length = v ++ [b] at h + simp only [List.length_append, List.length_singleton] at h + have ht := π.transcript_take X (m := v.length) (n := v.length + 1) (by omega) + rw [h] at ht + have hp : π.transcript X v.length = v := by simpa using ht.symm + rw [ScanRule.transcript_succ, hp] at h + have hb : X (π.query v) = b := by simpa using List.append_cancel_left h + exact ⟨hp, hb⟩ + · rintro ⟨hp, hb⟩ + change π.transcript X v.length = v at hp + simpa [event, ScanRule.transcript_succ, hp, hb] + +theorem event_children_union (π : ScanRule) (v : List Bool) : + event π (v ++ [false]) ∪ event π (v ++ [true]) = event π v := by + rw [event_snoc, event_snoc] + ext X + cases hb : X (π.query v) <;> simp [hb] + +theorem event_children_disjoint (π : ScanRule) (v : List Bool) : + Disjoint (event π (v ++ [false])) (event π (v ++ [true])) := by + rw [event_snoc, event_snoc] + apply Set.disjoint_left.mpr + intro X hX hY + exact Bool.false_ne_true (hX.2.symm.trans hY.2) + +theorem measure_event_children (μ : Measure Cantor) (π : ScanRule) (v : List Bool) : + μ (event π (v ++ [false])) + μ (event π (v ++ [true])) = μ (event π v) := by + rw [← measure_union (event_children_disjoint π v) (measurableSet_event π _), + event_children_union] + +/-- Advance the transcript and multiply capital by the next return factor. -/ +noncomputable def capitalStep (w : List Bool → ℝ) (p : List Bool × ℝ) (b : Bool) : + List Bool × ℝ := + (p.1 ++ [b], p.2 * (1 + (answerSign b : ℝ) * w p.1)) + +/-- The transcript and capital after applying each multiplicative update. -/ +noncomputable def account (w : List Bool → ℝ) (v : List Bool) : List Bool × ℝ := + v.foldl (capitalStep w) ([], 1) + +/-- The product of the return factors along the given transcript. -/ +noncomputable def capital (w : List Bool → ℝ) (v : List Bool) : ℝ := (account w v).2 + +@[simp] theorem account_snoc (w : List Bool → ℝ) (v : List Bool) (b : Bool) : + account w (v ++ [b]) = capitalStep w (account w v) b := by + simp [account, List.foldl_append] + +theorem account_prefix (w : List Bool → ℝ) (v : List Bool) : (account w v).1 = v := by + induction v using List.reverseRecOn with + | nil => rfl + | append_singleton v b ih => simp [capitalStep, ih] + +@[simp] theorem capital_nil (w : List Bool → ℝ) : capital w [] = 1 := rfl + +theorem capital_snoc (w : List Bool → ℝ) (v : List Bool) (b : Bool) : + capital w (v ++ [b]) = capital w v * (1 + (answerSign b : ℝ) * w v) := by + simp [capital, capitalStep, account_prefix] + +theorem factor_nonneg {w : ℝ} (hw : |w| ≤ 1) (b : Bool) : + 0 ≤ 1 + (answerSign b : ℝ) * w := by + obtain ⟨hl, hu⟩ := abs_le.mp hw + cases b <;> norm_num [answerSign] <;> linarith + +theorem capital_nonneg (w : List Bool → ℝ) (hw : ∀ v, |w v| ≤ 1) (v : List Bool) : + 0 ≤ capital w v := by + induction v using List.reverseRecOn with + | nil => norm_num + | append_singleton v b ih => + rw [capital_snoc] + exact mul_nonneg ih (factor_nonneg (hw v) b) + +theorem capital_fair (w : List Bool → ℝ) (v : List Bool) : + capital w (v ++ [false]) + capital w (v ++ [true]) = 2 * capital w v := by + simp only [capital_snoc, answerSign_false, answerSign_true, Rat.cast_neg, Rat.cast_one] + ring + +/-- The fair capital process induced by a schedule of wager fractions bounded by one. -/ +noncomputable def process (w : List Bool → ℝ) (hw : ∀ v, |w v| ≤ 1) : CapitalProcess where + value := capital w + initial := capital_nil w + nonneg := capital_nonneg w hw + fair := capital_fair w + +/-- `true` selects histories whose next bit is conditionally fair. -/ +noncomputable def fairWager (select : List Bool → Bool) (w : List Bool → ℝ) (v : List Bool) : ℝ := + if select v then w v else 0 + +/-- The original wager on forced answers and zero on fair answers. -/ +noncomputable def forcedWager (select : List Bool → Bool) (w : List Bool → ℝ) (v : List Bool) : ℝ := + if select v then 0 else w v + +/-- The magnitude of the original wager on forced answers and zero on fair answers. -/ +noncomputable def forcedAmount (select : List Bool → Bool) (w : List Bool → ℝ) + (v : List Bool) : ℝ := if select v then 0 else |w v| + +theorem fairWager_bound (select : List Bool → Bool) (w : List Bool → ℝ) + (hw : ∀ v, |w v| ≤ 1) (v : List Bool) : |fairWager select w v| ≤ 1 := by + cases h : select v <;> simp [fairWager, h, hw] + +theorem forcedWager_bound (select : List Bool → Bool) (w : List Bool → ℝ) + (hw : ∀ v, |w v| ≤ 1) (v : List Bool) : |forcedWager select w v| ≤ 1 := by + cases h : select v <;> simp [forcedWager, h, hw] + +@[simp] theorem abs_forcedWager (select : List Bool → Bool) (w : List Bool → ℝ) (v : List Bool) : + |forcedWager select w v| = forcedAmount select w v := by + cases h : select v <;> simp [forcedWager, forcedAmount, h] + +theorem forcedAmount_nonneg (select : List Bool → Bool) (w : List Bool → ℝ) (v : List Bool) : + 0 ≤ forcedAmount select w v := by + cases h : select v <;> simp [forcedAmount, h] + +/-- The condition consumed from the affine probability calculation. It is an +identity of actual transcript-cylinder probabilities under the input law. -/ +def FairLaw (μ : Measure Cantor) (π : ScanRule) (select : List Bool → Bool) : Prop := + ∀ v, select v = true → ∀ b : Bool, + μ (event π (v ++ [b])) = (1 / 2 : ℝ≥0∞) * μ (event π v) + +/-- Capital-weighted mass is conserved when refining each transcript cylinder. -/ +def WeightedBalance (μ : Measure Cantor) (π : ScanRule) (d : CapitalProcess) : Prop := + ∀ v, ENNReal.ofReal (d.value (v ++ [false])) * μ (event π (v ++ [false])) + + ENNReal.ofReal (d.value (v ++ [true])) * μ (event π (v ++ [true])) = + ENNReal.ofReal (d.value v) * μ (event π v) + +theorem fair_process_weightedBalance (μ : Measure Cantor) (π : ScanRule) + (select : List Bool → Bool) (w : List Bool → ℝ) (hw : ∀ v, |w v| ≤ 1) + (hfair : FairLaw μ π select) : + WeightedBalance μ π (process (fairWager select w) (fairWager_bound select w hw)) := by + let d := process (fairWager select w) (fairWager_bound select w hw) + change WeightedBalance μ π d + intro v + cases hs : select v with + | false => + have hchild (b : Bool) : d.value (v ++ [b]) = d.value v := by + change capital (fairWager select w) (v ++ [b]) = capital (fairWager select w) v + simp [capital_snoc, fairWager, hs] + rw [hchild, hchild, ← mul_add, measure_event_children] + | true => + rw [hfair v hs false, hfair v hs true, ← add_mul, + ← ENNReal.ofReal_add (d.nonneg _) (d.nonneg _), d.fair, + ENNReal.ofReal_mul (by norm_num : (0 : ℝ) ≤ 2)] + norm_num only [ENNReal.ofReal_ofNat] + calc + 2 * ENNReal.ofReal (d.value v) * ((1 / 2 : ℝ≥0∞) * μ (event π v)) = + ENNReal.ofReal (d.value v) * μ (event π v) * (2 * (1 / 2)) := by ac_rfl + _ = _ := by + rw [one_div, ENNReal.mul_inv_cancel (by norm_num) (by norm_num), mul_one] + +/-- Finite-tree maximal inequality under a nonuniform input law. -/ +theorem finiteHit_bound (μ : Measure Cantor) (π : ScanRule) (d : CapitalProcess) + (hbalance : WeightedBalance μ π d) (a : ℝ) (v : List Bool) (n : ℕ) : + ENNReal.ofReal a * μ (d.finiteHit π a v n) ≤ ENNReal.ofReal (d.value v) * μ (event π v) := by + induction n generalizing v with + | zero => + by_cases h : a < d.value v + · simp only [CapitalProcess.finiteHit, ite_eq_left h, event] + gcongr + · simp [CapitalProcess.finiteHit, h] + | succ n ih => + by_cases h : a < d.value v + · simp only [CapitalProcess.finiteHit, ite_eq_left h, event] + gcongr + · rw [CapitalProcess.finiteHit, ite_eq_right h] + calc + _ ≤ ENNReal.ofReal a * (μ (d.finiteHit π a (v ++ [false]) n) + + μ (d.finiteHit π a (v ++ [true]) n)) := by + gcongr + exact measure_union_le _ _ + _ = _ := mul_add _ _ _ + _ ≤ _ := add_le_add (ih _) (ih _) + _ = _ := hbalance v + +theorem measure_exceeds_pow_le (μ : Measure Cantor) [IsProbabilityMeasure μ] + (π : ScanRule) (d : CapitalProcess) (hbalance : WeightedBalance μ π d) (m : ℕ) : + μ (d.exceeds π ((2 : ℝ) ^ m)) ≤ (1 / 2 : ℝ≥0∞) ^ m := by + rw [d.exceeds_eq_iUnion_finiteHit, (d.finiteHit_mono π ((2 : ℝ) ^ m) []).measure_iUnion] + apply iSup_le + intro n + have h := finiteHit_bound μ π d hbalance ((2 : ℝ)^m) [] n + simp only [d.initial, ENNReal.ofReal_one, event_nil, measure_univ, mul_one, + ENNReal.ofReal_pow (by norm_num : (0 : ℝ) ≤ 2), ENNReal.ofReal_ofNat] at h + have hc : (1 / 2 : ℝ≥0∞)^m * (2 : ℝ≥0∞)^m = 1 := by + rw [← mul_pow, one_div, ENNReal.inv_mul_cancel (by norm_num) (by norm_num), one_pow] + calc + _ = (1 / 2 : ℝ≥0∞)^m * + ((2 : ℝ≥0∞)^m * μ (d.finiteHit π ((2 : ℝ)^m) [] n)) := by + rw [← mul_assoc, hc, one_mul] + _ ≤ (1 / 2 : ℝ≥0∞)^m * 1 := by gcongr + _ = _ := mul_one _ + +/-- The weighted maximal inequality implies almost-sure boundedness directly; +no martingale convergence theorem is needed. -/ +theorem ae_bounded_of_weightedBalance (μ : Measure Cantor) [IsProbabilityMeasure μ] + (π : ScanRule) (d : CapitalProcess) (hbalance : WeightedBalance μ π d) : + ∀ᵐ X ∂μ, ∃ B : ℝ, ∀ n, d.value (π.transcript X n) ≤ B := by + rw [ae_iff] + let Bad : Set Cantor := {X | ¬∃ B : ℝ, ∀ n, d.value (π.transcript X n) ≤ B} + have hbound (m : ℕ) : μ Bad ≤ (1 / 2 : ℝ≥0∞)^m := by + apply (measure_mono (show Bad ⊆ d.exceeds π ((2 : ℝ)^m) from ?_)).trans + (measure_exceeds_pow_le μ π d hbalance m) + intro X hX + by_contra h + apply hX + refine ⟨(2 : ℝ)^m, fun n => ?_⟩ + exact le_of_not_gt (fun hn => h ⟨n, hn⟩) + have hzero : μ Bad ≤ 0 := + le_of_tendsto_of_tendsto tendsto_const_nhds + (ENNReal.tendsto_pow_atTop_nhds_zero_of_lt_one (by norm_num : (1 / 2 : ℝ≥0∞) < 1)) + (Filter.Eventually.of_forall hbound) + exact le_antisymm hzero bot_le + +/-- The full capital is the product of the fair-only and forced-only accounts. -/ +theorem capital_eq_fair_mul_forced (select : List Bool → Bool) (w : List Bool → ℝ) + (v : List Bool) : + capital w v = capital (fairWager select w) v * capital (forcedWager select w) v := by + induction v using List.reverseRecOn with + | nil => simp + | append_singleton v b ih => + simp only [capital_snoc, ih] + cases hs : select v <;> simp [fairWager, forcedWager, hs] <;> ring + +theorem factor_le_exp_abs (w : ℝ) (b : Bool) : + 1 + (answerSign b : ℝ) * w ≤ Real.exp |w| := by + calc + _ ≤ |w| + 1 := by + cases b <;> norm_num [answerSign] <;> linarith [le_abs_self w, neg_le_abs w] + _ ≤ _ := Real.add_one_le_exp _ + +/-- A multiplicative account is bounded by the exponential of its finite +absolute-wager sum. -/ +theorem capital_le_exp_sum (w : List Bool → ℝ) (hw : ∀ v, |w v| ≤ 1) + (π : ScanRule) (X : Cantor) (n : ℕ) : + capital w (π.transcript X n) ≤ + Real.exp (∑ t ∈ Finset.range n, |w (π.transcript X t)|) := by + induction n with + | zero => simp + | succ n ih => + rw [ScanRule.transcript_succ, capital_snoc, Finset.sum_range_succ, Real.exp_add] + exact mul_le_mul ih (factor_le_exp_abs _ _) + (factor_nonneg (hw _) _) (Real.exp_pos _).le + +/-- Fair-step capital is almost surely bounded under the actual input law. +The other steps are skipped, without making any assumption about their answer law. -/ +theorem ae_bounded_fair_capital (μ : Measure Cantor) [IsProbabilityMeasure μ] + (π : ScanRule) (select : List Bool → Bool) (w : List Bool → ℝ) + (hw : ∀ v, |w v| ≤ 1) (hfair : FairLaw μ π select) : + ∀ᵐ X ∂μ, ∃ B : ℝ, ∀ n, capital (fairWager select w) (π.transcript X n) ≤ B := + ae_bounded_of_weightedBalance μ π _ (fair_process_weightedBalance μ π select w hw hfair) + +/-- The main fair/forced criterion. Fairness of selected histories and almost-sure +summability of all other absolute wagers imply bounded total capital almost surely. +These hypotheses must be established for the intended block product law. -/ +theorem ae_bounded_capital (μ : Measure Cantor) [IsProbabilityMeasure μ] + (π : ScanRule) (select : List Bool → Bool) (w : List Bool → ℝ) + (hw : ∀ v, |w v| ≤ (1 / 2 : ℝ)) (hfair : FairLaw μ π select) + (hforced : ∀ᵐ X ∂μ, Summable (fun n => forcedAmount select w (π.transcript X n))) : + ∀ᵐ X ∂μ, ∃ B : ℝ, ∀ n, capital w (π.transcript X n) ≤ B := by + have hw' (v : List Bool) : |w v| ≤ 1 := (hw v).trans (by norm_num) + filter_upwards [ae_bounded_fair_capital μ π select w hw' hfair, hforced] + with X hF hsum + obtain ⟨B, hB⟩ := hF + let A := ∑' n, forcedAmount select w (π.transcript X n) + refine ⟨max 0 B * Real.exp A, fun n => ?_⟩ + have hsum_le : (∑ t ∈ Finset.range n, forcedAmount select w (π.transcript X t)) ≤ A := + hsum.sum_le_tsum _ (fun _ _ => forcedAmount_nonneg _ _ _) + have hG : capital (forcedWager select w) (π.transcript X n) ≤ Real.exp A := by + calc + _ ≤ Real.exp (∑ t ∈ Finset.range n, + forcedAmount select w (π.transcript X t)) := by + simpa only [abs_forcedWager] using + capital_le_exp_sum (forcedWager select w) (forcedWager_bound select w hw') π X n + _ ≤ _ := Real.exp_le_exp.mpr hsum_le + rw [capital_eq_fair_mul_forced select] + exact mul_le_mul ((hB n).trans (le_max_right _ _)) hG + (capital_nonneg _ (forcedWager_bound select w hw') _) (le_max_left _ _) + +/-- Reconstructing a capital process from its own wagers recovers the original +values, including branches whose capital reaches zero. -/ +theorem capital_wager_eq (d : CapitalProcess) (v : List Bool) : + capital d.wager v = d.value v := by + induction v using List.reverseRecOn with + | nil => simp [d.initial] + | append_singleton v b ih => + rw [capital_snoc, ih] + by_cases hz : d.value v = 0 + · rw [d.successor_eq_zero v hz b, hz] + simp + · have hp : 0 < d.value v := lt_of_le_of_ne (d.nonneg v) (Ne.symm hz) + rw [d.update v hp b] + cases b <;> simp [answerSign] + +/-- The criterion applied directly to an existing fair capital process. -/ +theorem ae_bounded_process (μ : Measure Cantor) [IsProbabilityMeasure μ] + (π : ScanRule) (select : List Bool → Bool) (d : CapitalProcess) + (hw : ∀ v, |d.wager v| ≤ (1 / 2 : ℝ)) (hfair : FairLaw μ π select) + (hforced : ∀ᵐ X ∂μ, + Summable (fun n => forcedAmount select d.wager (π.transcript X n))) : + ∀ᵐ X ∂μ, ∃ B : ℝ, ∀ n, d.value (π.transcript X n) ≤ B := by + simpa only [capital_wager_eq] using ae_bounded_capital μ π select d.wager hw hfair hforced + +end Klr.FairForced + +namespace Klr + +open MeasureTheory + +/-- A strategy fails almost surely when its selected steps are fair and its +remaining absolute wagers are almost surely summable. -/ +theorem BettingStrategy.ae_not_succeeds_of_fair_forced (s : BettingStrategy) + (μ : Measure Cantor) [IsProbabilityMeasure μ] (select : List Bool → Bool) + (hw : ∀ v, |s.capital.wager v| ≤ (1 / 2 : ℝ)) + (hfair : FairForced.FairLaw μ s.scan select) + (hforced : ∀ᵐ X ∂μ, + Summable (fun n => FairForced.forcedAmount select s.capital.wager (s.scan.transcript X n))) : + ∀ᵐ X ∂μ, ¬ s.Succeeds X := by + filter_upwards [FairForced.ae_bounded_process μ s.scan select s.capital hw hfair hforced] + with X hX + obtain ⟨B, hB⟩ := hX + intro hs + obtain ⟨n, hn⟩ := hs B + exact (not_lt_of_ge (hB n)) hn + +end Klr diff --git a/LeanPool/KLRandomness/FiniteMeasure.lean b/LeanPool/KLRandomness/FiniteMeasure.lean new file mode 100644 index 0000000000..e1c69e765d --- /dev/null +++ b/LeanPool/KLRandomness/FiniteMeasure.lean @@ -0,0 +1,202 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.Cantor +public import Mathlib.Probability.Independence.InfinitePi +public import Mathlib.Data.ZMod.Basic +public import Mathlib.SetTheory.Cardinal.Finite +public import Mathlib.Data.Set.Finite.Basic +import Mathlib.Tactic.FunProp +import Mathlib.Tactic.NormNum + +/-! +# Finite-coordinate counting and fair-coin probabilities + +An injective choice of finitely many input coordinates has the uniform law on +binary assignments. Consequently the probability of any event on those +coordinates is its finite cardinality times the probability of one assignment. +The same statements are transported to `ZMod 2`, so finite linear-algebra counts +can be used directly with the concrete measure `Klr.fairCoin`. +-/ + +@[expose] public section + +namespace Klr.FiniteMeasure + +open MeasureTheory +open scoped ENNReal + +variable {ι : Type*} + +/-- Read the finite collection of coordinates specified by `e`. -/ +def coordinateBits (e : ι → ℕ) (X : Cantor) : ι → Bool := fun i => X (e i) + +theorem measurable_coordinateBits (e : ι → ℕ) : Measurable (coordinateBits e) := by + unfold coordinateBits + fun_prop + +/-- Distinct coordinates have precisely the product fair-bit law. -/ +theorem fairCoin_map_coordinates [Fintype ι] (e : ι → ℕ) (he : Function.Injective e) : + fairCoin.map (coordinateBits e) = Measure.pi (fun _ : ι => fairBit) := by + unfold fairCoin coordinateBits + rw [Measure.map_infinitePi_infinitePi_of_inj he, Measure.infinitePi_eq_pi] + +/-- Every assignment to the finite coordinates has probability `2⁻|ι|`. -/ +theorem fairCoin_coordinate_singleton [Fintype ι] (e : ι → ℕ) (he : Function.Injective e) + (b : ι → Bool) : + fairCoin {X | coordinateBits e X = b} = (1 / 2 : ℝ≥0∞) ^ Fintype.card ι := by + change fairCoin (coordinateBits e ⁻¹' {b}) = _ + rw [← Measure.map_apply (measurable_coordinateBits e) (measurableSet_singleton b), + fairCoin_map_coordinates e he, Measure.pi_singleton] + simp + +/-- The fair product measure on a finite set assigns equal mass to every point. -/ +theorem finite_product_apply [Fintype ι] (S : Set (ι → Bool)) : + (Measure.pi (fun _ : ι => fairBit)) S = + (Nat.card S : ℝ≥0∞) * (1 / 2 : ℝ≥0∞) ^ Fintype.card ι := by + classical + let _ := Fintype.ofFinite S + calc + (Measure.pi (fun _ : ι => fairBit)) S = + ∑ b ∈ S.toFinite.toFinset, (Measure.pi (fun _ : ι => fairBit)) {b} := by + rw [sum_measure_singleton, S.toFinite.coe_toFinset] + _ = (S.toFinite.toFinset.card : ℝ≥0∞) * + (1 / 2 : ℝ≥0∞) ^ Fintype.card ι := by simp [Measure.pi_singleton] + _ = _ := by rw [S.toFinite.card_toFinset, Nat.card_eq_fintype_card] + +/-- Probability of any event depending on finitely many distinct coordinates. -/ +theorem fairCoin_coordinate_event [Fintype ι] (e : ι → ℕ) (he : Function.Injective e) + (S : Set (ι → Bool)) : + fairCoin {X | coordinateBits e X ∈ S} = + (Nat.card S : ℝ≥0∞) * (1 / 2 : ℝ≥0∞) ^ Fintype.card ι := by + change fairCoin (coordinateBits e ⁻¹' S) = _ + rw [← Measure.map_apply (measurable_coordinateBits e) S.toFinite.measurableSet, + fairCoin_map_coordinates e he, finite_product_apply] + +/-- The canonical identification of a bit with its value in the two-element field. -/ +def boolEquivF2 : Bool ≃ ZMod 2 := + finTwoEquiv.symm.trans (ZMod.finEquiv 2).toEquiv + +@[simp] theorem boolEquivF2_false : boolEquivF2 false = 0 := rfl + +@[simp] theorem boolEquivF2_true : boolEquivF2 true = 1 := rfl + +/-- Apply the bit/field identification to every coordinate. -/ +def assignmentEquivF2 : (ι → Bool) ≃ (ι → ZMod 2) := + Equiv.piCongrRight (fun _ => boolEquivF2) + +/-- Finite coordinates of a binary input, regarded as elements of `ZMod 2`. -/ +def coordinateValues (e : ι → ℕ) (X : Cantor) : ι → ZMod 2 := + assignmentEquivF2 (coordinateBits e X) + +@[simp] theorem coordinateValues_apply (e : ι → ℕ) (X : Cantor) (i : ι) : + coordinateValues e X i = boolEquivF2 (X (e i)) := rfl + +theorem measurableSet_coordinate_event_f2 [Finite ι] (e : ι → ℕ) + (S : Set (ι → ZMod 2)) : + MeasurableSet {X | coordinateValues e X ∈ S} := by + exact (assignmentEquivF2 ⁻¹' S).toFinite.measurableSet.preimage + (measurable_coordinateBits e) + +/-- Linear-algebraic assignment sets have exactly their finite counting probabilities. -/ +theorem fairCoin_coordinate_event_f2 [Fintype ι] (e : ι → ℕ) (he : Function.Injective e) + (S : Set (ι → ZMod 2)) : + fairCoin {X | coordinateValues e X ∈ S} = + (Nat.card S : ℝ≥0∞) * (1 / 2 : ℝ≥0∞) ^ Fintype.card ι := by + change fairCoin {X | coordinateBits e X ∈ assignmentEquivF2 ⁻¹' S} = _ + rw [fairCoin_coordinate_event e he] + have hc : Nat.card (assignmentEquivF2 ⁻¹' S) = Nat.card S := + Nat.card_congr (assignmentEquivF2.subtypeEquiv (fun _ => Iff.rfl)) + rw [hc] + +/-- A finite cardinality ratio by `2^r` gives the same exact fair-coin probability ratio. -/ +theorem fairCoin_coordinate_factor_of_card [Finite ι] (e : ι → ℕ) + (he : Function.Injective e) + (A B : Set (ι → ZMod 2)) (r : ℕ) + (hcard : Nat.card A * 2 ^ r = Nat.card B) : + fairCoin {X | coordinateValues e X ∈ A} = + (1 / 2 : ℝ≥0∞) ^ r * fairCoin {X | coordinateValues e X ∈ B} := by + let _ := Fintype.ofFinite ι + rw [fairCoin_coordinate_event_f2 e he, fairCoin_coordinate_event_f2 e he] + have hc : (Nat.card A : ℝ≥0∞) * (2 : ℝ≥0∞) ^ r = Nat.card B := by + exact_mod_cast hcard + rw [← hc] + have hcancel : (1 / 2 : ℝ≥0∞) ^ r * (2 : ℝ≥0∞) ^ r = 1 := by + rw [← mul_pow] + rw [one_div, ENNReal.inv_mul_cancel (by norm_num) (by norm_num), one_pow] + calc + (Nat.card A : ℝ≥0∞) * (1 / 2 : ℝ≥0∞) ^ Fintype.card ι = + (Nat.card A : ℝ≥0∞) * + ((1 / 2 : ℝ≥0∞) ^ r * (2 : ℝ≥0∞) ^ r) * + (1 / 2 : ℝ≥0∞) ^ Fintype.card ι := by rw [hcancel, mul_one] + _ = _ := by ac_rfl + +/-- The singleton formula specialized to a finite set of input positions. -/ +theorem fairCoin_restrict_singleton (G : Finset ℕ) (b : G → Bool) : + fairCoin {X : Cantor | (fun i : G => X i) = b} = + (1 / 2 : ℝ≥0∞) ^ G.card := by + change fairCoin {X | coordinateBits (fun i : G => (i : ℕ)) X = b} = _ + simpa using + fairCoin_coordinate_singleton (fun i : G => (i : ℕ)) Subtype.val_injective b + +/-- The counting formula specialized to a finite set of input positions. -/ +theorem fairCoin_restrict_event (G : Finset ℕ) (S : Set (G → Bool)) : + fairCoin {X : Cantor | (fun i : G => X i) ∈ S} = + (Nat.card S : ℝ≥0∞) * (1 / 2 : ℝ≥0∞) ^ G.card := by + change fairCoin {X | coordinateBits (fun i : G => (i : ℕ)) X ∈ S} = _ + simpa using + fairCoin_coordinate_event (fun i : G => (i : ℕ)) Subtype.val_injective S + +private def splitAssignmentEquiv {κ : Type*} (S : Set (ι → Bool)) + (T : Set (κ → Bool)) : + {z : ι ⊕ κ → Bool // (fun i => z (.inl i)) ∈ S ∧ (fun j => z (.inr j)) ∈ T} ≃ + S × T where + toFun z := (⟨fun i => z.val (.inl i), z.property.1⟩, + ⟨fun j => z.val (.inr j), z.property.2⟩) + invFun z := ⟨Sum.elim z.1.val z.2.val, z.1.property, z.2.property⟩ + left_inv z := by + apply Subtype.ext + funext k + cases k <;> rfl + right_inv z := by + rcases z with ⟨⟨s, hs⟩, ⟨t, ht⟩⟩ + rfl + +/-- Events on disjoint finite collections of fair-coin coordinates are independent. -/ +theorem fairCoin_coordinate_events_disjoint {κ : Type*} [Finite ι] [Finite κ] + (e : ι → ℕ) (he : Function.Injective e) (f : κ → ℕ) (hf : Function.Injective f) + (hdisjoint : ∀ i j, e i ≠ f j) (S : Set (ι → Bool)) (T : Set (κ → Bool)) : + fairCoin {X | coordinateBits e X ∈ S ∧ coordinateBits f X ∈ T} = + fairCoin {X | coordinateBits e X ∈ S} * + fairCoin {X | coordinateBits f X ∈ T} := by + let _ := Fintype.ofFinite ι + let _ := Fintype.ofFinite κ + let U : Set (ι ⊕ κ → Bool) := + {z | (fun i => z (.inl i)) ∈ S ∧ (fun j => z (.inr j)) ∈ T} + change fairCoin {X | coordinateBits (Sum.elim e f) X ∈ U} = _ + rw [fairCoin_coordinate_event _ (he.sumElim hf hdisjoint), + fairCoin_coordinate_event e he, fairCoin_coordinate_event f hf] + have hcard : Nat.card U = Nat.card S * Nat.card T := by + exact (Nat.card_congr (splitAssignmentEquiv S T)).trans (Nat.card_prod S T) + rw [hcard, Nat.cast_mul, Fintype.card_sum, pow_add] + ac_rfl + +/-- Independence of finite disjoint coordinate events, in binary-field coordinates. -/ +theorem fairCoin_coordinate_events_disjoint_f2 {κ : Type*} [Finite ι] [Finite κ] + (e : ι → ℕ) (he : Function.Injective e) (f : κ → ℕ) (hf : Function.Injective f) + (hdisjoint : ∀ i j, e i ≠ f j) + (S : Set (ι → ZMod 2)) (T : Set (κ → ZMod 2)) : + fairCoin {X | coordinateValues e X ∈ S ∧ coordinateValues f X ∈ T} = + fairCoin {X | coordinateValues e X ∈ S} * + fairCoin {X | coordinateValues f X ∈ T} := + fairCoin_coordinate_events_disjoint e he f hf hdisjoint + (assignmentEquivF2 ⁻¹' S) (assignmentEquivF2 ⁻¹' T) + +end Klr.FiniteMeasure diff --git a/LeanPool/KLRandomness/FiniteProbability.lean b/LeanPool/KLRandomness/FiniteProbability.lean new file mode 100644 index 0000000000..a5bd9e9e41 --- /dev/null +++ b/LeanPool/KLRandomness/FiniteProbability.lean @@ -0,0 +1,180 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import Mathlib.Basic.Real.Basic +public import Mathlib.Algebra.Order.BigOperators.Group.Finset +public import Mathlib.Algebra.BigOperators.Field +public import Mathlib.Algebra.BigOperators.Ring.Finset +public import Mathlib.SetTheory.Cardinal.Finite +import Mathlib.Tactic.NormNum + +/-! +# Uniform probabilities on finite sample spaces + +The candidate-list construction uses only finite uniform experiments. These +definitions expose their actual normalized counting probabilities and averages; +independence of repeated samples follows from finite product sums. +-/ + +@[expose] public section + +namespace Klr.FiniteProbability + +open scoped BigOperators + +variable {Ω : Type*} [Fintype Ω] + +/-- The uniform average of a real-valued function on a finite type. -/ +noncomputable def average (f : Ω → ℝ) : ℝ := (∑ x, f x) / Fintype.card Ω + +/-- The actual uniform counting probability of a finite event. -/ +noncomputable def probability (A : Set Ω) : ℝ := by + classical + exact average (fun x => if x ∈ A then 1 else 0) + +theorem probability_eq_card (A : Set Ω) : + probability A = (Nat.card A : ℝ) / Fintype.card Ω := by + classical + simp [probability, average, Nat.card_eq_fintype_card, Fintype.card_subtype] + +theorem average_congr {f g : Ω → ℝ} (h : ∀ x, f x = g x) : average f = average g := by + simp only [average, funext h] + +theorem average_nonneg {f : Ω → ℝ} (hf : ∀ x, 0 ≤ f x) : 0 ≤ average f := by + exact div_nonneg (Finset.sum_nonneg fun x _ => hf x) (Nat.cast_nonneg _) + +theorem average_mono {f g : Ω → ℝ} (h : ∀ x, f x ≤ g x) : average f ≤ average g := by + exact div_le_div_of_nonneg_right (Finset.sum_le_sum fun x _ => h x) (Nat.cast_nonneg _) + +theorem average_add (f g : Ω → ℝ) : + average (fun x => f x + g x) = average f + average g := by + simp [average, Finset.sum_add_distrib, add_div] + +theorem average_sub (f g : Ω → ℝ) : + average (fun x => f x - g x) = average f - average g := by + simp [average, Finset.sum_sub_distrib, sub_div] + +theorem average_const_mul (c : ℝ) (f : Ω → ℝ) : + average (fun x => c * f x) = c * average f := by + simp [average, ← Finset.mul_sum, mul_div_assoc] + +theorem average_mul_const (f : Ω → ℝ) (c : ℝ) : + average (fun x => f x * c) = average f * c := by + simp [average, ← Finset.sum_mul, div_mul_eq_mul_div] + +theorem average_sum {ι : Type*} [Fintype ι] (f : ι → Ω → ℝ) : + average (fun x => ∑ i, f i x) = ∑ i, average (f i) := by + unfold average + rw [Finset.sum_comm, Finset.sum_div] + +theorem probability_nonneg (A : Set Ω) : 0 ≤ probability A := by + classical + exact average_nonneg fun x => by split_ifs <;> norm_num + +theorem probability_mono {A B : Set Ω} (h : A ⊆ B) : probability A ≤ probability B := by + classical + apply average_mono + intro x + by_cases hx : x ∈ A + · have hy := h hx + simp [hx, hy] + · simp only [ite_eq_right hx] + split_ifs <;> norm_num + +@[simp] theorem probability_empty : probability (∅ : Set Ω) = 0 := by + simp [probability, average] + +theorem probability_iUnion_le {ι : Type*} [Fintype ι] (A : ι → Set Ω) : + probability (⋃ i, A i) ≤ ∑ i, probability (A i) := by + classical + change average (fun x => if x ∈ ⋃ i, A i then (1 : ℝ) else 0) ≤ + ∑ i, average (fun x => if x ∈ A i then (1 : ℝ) else 0) + rw [← average_sum] + apply average_mono + intro x + by_cases hx : x ∈ ⋃ i, A i + · obtain ⟨i, hi⟩ := Set.mem_iUnion.mp hx + have hs : (1 : ℝ) ≤ ∑ j, if x ∈ A j then (1 : ℝ) else 0 := by + simpa only [ite_eq_left hi] using + (Finset.single_le_sum (f := fun j => if x ∈ A j then (1 : ℝ) else 0) + (fun j _ => by split_ifs <;> norm_num) (Finset.mem_univ i)) + simpa only [ite_eq_left hx] using hs + · simp only [ite_eq_right hx] + exact Finset.sum_nonneg fun i _ => by split_ifs <;> norm_num + +section Nonempty + +variable [Nonempty Ω] + +theorem card_pos : (0 : ℝ) < Fintype.card Ω := by exact_mod_cast Fintype.card_pos + +@[simp] theorem average_const (c : ℝ) : average (fun _ : Ω => c) = c := by + have hc : (Fintype.card Ω : ℝ) ≠ 0 := ne_of_gt (card_pos (Ω := Ω)) + simp [average, hc] + +@[simp] theorem probability_univ : probability (Set.univ : Set Ω) = 1 := by + simp [probability] + +theorem probability_le_one (A : Set Ω) : probability A ≤ 1 := by + simpa using probability_mono (Set.subset_univ A) + +theorem probability_compl (A : Set Ω) : probability Aᶜ = 1 - probability A := by + classical + calc + probability Aᶜ = average (fun x => 1 - (if x ∈ A then (1 : ℝ) else 0)) := by + apply average_congr + intro x + by_cases hx : x ∈ A <;> simp [hx] + _ = 1 - probability A := by rw [average_sub, average_const]; rfl + +omit [Nonempty Ω] in +/-- The finite Markov bound for a nonnegative random variable. -/ +theorem probability_le_average_div (f : Ω → ℝ) (hf : ∀ x, 0 ≤ f x) + (a : ℝ) (ha : 0 < a) : probability {x | a ≤ f x} ≤ average f / a := by + classical + apply (le_div_iff₀ ha).mpr + change average (fun x => if a ≤ f x then (1 : ℝ) else 0) * a ≤ average f + rw [← average_mul_const] + apply average_mono + intro x + by_cases hx : a ≤ f x + · simpa only [Set.mem_ofPred_eq, ite_eq_left hx, one_mul] using hx + · simpa only [Set.mem_ofPred_eq, ite_eq_right hx, zero_mul] using hf x + +/-- A finite experiment with failure probability less than one has a successful outcome. -/ +theorem exists_not_mem_of_probability_lt_one (A : Set Ω) (h : probability A < 1) : + ∃ x, x ∉ A := by + by_contra hn + have he : A = Set.univ := Set.eq_univ_of_forall (by simpa using hn) + simp [he] at h + +end Nonempty + +/-- Product averages factor, expressing independence of the actual finite uniform samples. -/ +theorem average_prod_samples (f : Ω → ℝ) (J : ℕ) : + average (fun z : Fin J → Ω => ∏ i, f (z i)) = (average f) ^ J := by + unfold average + rw [← Fintype.sum_pow] + simp [div_pow] + +/-- Taking the uniform average on a product is iterated uniform averaging. -/ +theorem average_prod {Γ : Type*} [Fintype Γ] (f : Ω × Γ → ℝ) : + average f = average (fun x : Ω => average (fun y : Γ => f (x, y))) := by + unfold average + rw [Fintype.sum_prod_type] + simp only [Fintype.card_prod, Nat.cast_mul, ← Finset.sum_div, div_div, mul_comm] + +/-- The probability of an event on a product is the average of its fiber probabilities. -/ +theorem probability_prod_fiber {Γ : Type*} [Fintype Γ] (A : Set (Ω × Γ)) : + probability A = average (fun x : Ω => probability {y : Γ | (x, y) ∈ A}) := by + classical + exact average_prod _ + +end Klr.FiniteProbability diff --git a/LeanPool/KLRandomness/FiniteStage.lean b/LeanPool/KLRandomness/FiniteStage.lean new file mode 100644 index 0000000000..024084931f --- /dev/null +++ b/LeanPool/KLRandomness/FiniteStage.lean @@ -0,0 +1,177 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.AffineObservation +public import LeanPool.KLRandomness.FiniteMeasure +public import LeanPool.KLRandomness.ScanMeasure +public import Mathlib.Probability.ConditionalProbability +public import Mathlib.Logic.Function.DependsOn + +/-! +# Finite-stage affine identities for adaptive transcripts + +Fix finitely many distinct input coordinates. The old constraints and the +specified transcript depend on an observed part of those coordinates. If the +new constraint's map on the complementary unread coordinates is surjective, +each syndrome cuts the probability of every observed event by exactly `2⁻ʳ`. + +The conditional version uses Mathlib's actual conditional measure. Its +intersection identity also holds for zero-probability transcript events; it +does not divide by the probability of a transcript. +-/ + +@[expose] public section + +namespace Klr.FiniteStage + +open MeasureTheory ProbabilityTheory +open AffineObservation FiniteMeasure +open scoped ENNReal + +variable {ι : Type*} {r : ℕ} + +/-- An event specified by a condition on some of the finite input coordinates. -/ +def observedEvent (e : ι → ℕ) (O : Set ι) (P : (O → ZMod 2) → Prop) : Set Cantor := + {X | P (observedPart O (coordinateValues e X))} + +/-- The event that a finite system of parity equations has the specified syndrome. -/ +def affineEvent (e : ι → ℕ) + (D : (ι → ZMod 2) →ₗ[ZMod 2] (Fin r → ZMod 2)) + (y : Fin r → ZMod 2) : Set Cantor := + {X | D (coordinateValues e X) = y} + +theorem measurableSet_observedEvent [Finite ι] (e : ι → ℕ) (O : Set ι) + (P : (O → ZMod 2) → Prop) : MeasurableSet (observedEvent e O P) := + measurableSet_coordinate_event_f2 e (background O P) + +theorem measurableSet_affineEvent [Finite ι] (e : ι → ℕ) + (D : (ι → ZMod 2) →ₗ[ZMod 2] (Fin r → ZMod 2)) + (y : Fin r → ZMod 2) : MeasurableSet (affineEvent e D y) := + measurableSet_coordinate_event_f2 e {x | D x = y} + +/-- Any event depending only on the observed input positions has an observed-value predicate. +This converts a support condition into the representation used by the counting theorem. -/ +theorem exists_observedEvent_of_dependsOn (e : ι → ℕ) (O : Set ι) (A : Set Cantor) + (hA : DependsOn (fun X : Cantor => X ∈ A) (e '' O)) : + ∃ P : (O → ZMod 2) → Prop, A = observedEvent e O P := by + have hf : Function.FactorsThrough (fun X : Cantor => X ∈ A) + (fun X => observedPart O (coordinateValues e X)) := by + intro X Y h + apply hA + rintro n ⟨i, hi, rfl⟩ + exact boolEquivF2.injective (congrFun h ⟨i, hi⟩) + obtain ⟨P, hP⟩ := (Function.factorsThrough_iff _).mp hf + refine ⟨P, ?_⟩ + ext X + exact iff_of_eq (congrFun hP X) + +/-- Events depending on disjoint finite sets of input positions are independent. -/ +theorem fairCoin_inter_of_disjoint_support (A B : Set Cantor) (H I : Finset ℕ) + (hA : DependsOn (fun X : Cantor => X ∈ A) (H : Set ℕ)) + (hB : DependsOn (fun X : Cantor => X ∈ B) (I : Set ℕ)) + (hdis : Disjoint H I) : fairCoin (A ∩ B) = fairCoin A * fairCoin B := by + obtain ⟨P, hP⟩ := dependsOn_iff_exists_comp.mp hA + obtain ⟨Q, hQ⟩ := dependsOn_iff_exists_comp.mp hB + have heA : A = {X | coordinateBits (fun i : H => i.val) X ∈ {o | P o}} := by + ext X + exact iff_of_eq (congrFun hP X) + have heB : B = {X | coordinateBits (fun i : I => i.val) X ∈ {o | Q o}} := by + ext X + exact iff_of_eq (congrFun hQ X) + rw [heA, heB] + apply fairCoin_coordinate_events_disjoint _ Subtype.val_injective _ Subtype.val_injective + intro i j h + apply Finset.disjoint_left.mp hdis i.property + simpa only [h] using j.property + +@[simp] theorem observedEvent_and (e : ι → ℕ) (O : Set ι) + (P Q : (O → ZMod 2) → Prop) : + observedEvent e O (fun o => P o ∧ Q o) = + observedEvent e O P ∩ observedEvent e O Q := rfl + +/-- Full unread rank gives an exact syndrome factor for any observed background. -/ +theorem fairCoin_observed_inter_affine [Finite ι] (e : ι → ℕ) + (he : Function.Injective e) + (D : (ι → ZMod 2) →ₗ[ZMod 2] (Fin r → ZMod 2)) + (O : Set ι) [DecidablePred (· ∈ O)] (P : (O → ZMod 2) → Prop) + (y : Fin r → ZMod 2) (hD : Function.Surjective (unreadMap D O)) : + fairCoin (observedEvent e O P ∩ affineEvent e D y) = + (1 / 2 : ℝ≥0∞) ^ r * fairCoin (observedEvent e O P) := by + let _ := Fintype.ofFinite ι + exact fairCoin_coordinate_factor_of_card e he (joint D O P y) (background O P) r + (card_joint_mul_pow_eq_card_background D O P y hD) + +/-- The exact factor persists after conditioning on any earlier observed-coordinate event. +No positive-probability assumption on the transcript event `Q` is needed. -/ +theorem cond_observed_inter_affine [Finite ι] (e : ι → ℕ) + (he : Function.Injective e) + (D : (ι → ZMod 2) →ₗ[ZMod 2] (Fin r → ZMod 2)) + (O : Set ι) [DecidablePred (· ∈ O)] (P Q : (O → ZMod 2) → Prop) + (y : Fin r → ZMod 2) (hD : Function.Surjective (unreadMap D O)) : + (cond fairCoin (observedEvent e O P)) + (observedEvent e O Q ∩ affineEvent e D y) = + (1 / 2 : ℝ≥0∞) ^ r * + (cond fairCoin (observedEvent e O P)) (observedEvent e O Q) := by + rw [cond_apply (measurableSet_observedEvent e O P), + cond_apply (measurableSet_observedEvent e O P), ← Set.inter_assoc, + ← observedEvent_and, + fairCoin_observed_inter_affine e he D O (fun o => P o ∧ Q o) y hD] + rw [observedEvent_and] + ac_rfl + +/-- Under a nonnull earlier background, every syndrome still has probability `2⁻ʳ`. -/ +theorem cond_affine [Finite ι] (e : ι → ℕ) (he : Function.Injective e) + (D : (ι → ZMod 2) →ₗ[ZMod 2] (Fin r → ZMod 2)) + (O : Set ι) [DecidablePred (· ∈ O)] (P : (O → ZMod 2) → Prop) + (y : Fin r → ZMod 2) (hD : Function.Surjective (unreadMap D O)) + (hP : fairCoin (observedEvent e O P) ≠ 0) : + (cond fairCoin (observedEvent e O P)) (affineEvent e D y) = + (1 / 2 : ℝ≥0∞) ^ r := by + rw [cond_apply (measurableSet_observedEvent e O P), + fairCoin_observed_inter_affine e he D O P y hD, mul_left_comm, + ENNReal.inv_mul_cancel hP (measure_ne_top _ _), mul_one] + +/-- The fixed transcript's requirements, written as a predicate on observed coordinates. -/ +def transcriptPredicate (v : List Bool) {O : Set ι} (q : Fin v.length → O) + (o : O → ZMod 2) : Prop := + ∀ i, o (q i) = boolEquivF2 (v.getD i.val false) + +/-- Once a finite adaptive transcript is fixed, its queries are fixed coordinates. -/ +theorem transcriptEvent_eq_observedEvent (e : ι → ℕ) (O : Set ι) + (π : ScanRule) (v : List Bool) (q : Fin v.length → O) + (hq : ∀ i, e (q i).val = π.query (v.take i.val)) : + {X | π.transcript X v.length = v} = + observedEvent e O (transcriptPredicate v q) := by + ext X + rw [Set.mem_ofPred_eq, π.transcript_eq_iff] + change (∀ i < v.length, X (π.query (v.take i)) = v.getD i false) ↔ + ∀ i : Fin v.length, + boolEquivF2 (X (e (q i).val)) = boolEquivF2 (v.getD i.val false) + simp only [hq, Equiv.apply_eq_iff_eq] + exact ⟨fun h i => h i.val i.isLt, fun h i hi => h ⟨i, hi⟩⟩ + +/-- The paper's finite-stage intersection identity. Earlier constraints are encoded by `P`; +their coordinates and the transcript's queries lie in `O`. The unread columns of the new +constraint are required to have full row rank, expressed by surjectivity. -/ +theorem cond_transcript_inter_affine [Finite ι] (e : ι → ℕ) + (he : Function.Injective e) + (D : (ι → ZMod 2) →ₗ[ZMod 2] (Fin r → ZMod 2)) + (O : Set ι) [DecidablePred (· ∈ O)] (P : (O → ZMod 2) → Prop) + (π : ScanRule) (v : List Bool) (q : Fin v.length → O) + (hq : ∀ i, e (q i).val = π.query (v.take i.val)) + (y : Fin r → ZMod 2) (hD : Function.Surjective (unreadMap D O)) : + (cond fairCoin (observedEvent e O P)) + ({X | π.transcript X v.length = v} ∩ affineEvent e D y) = + (1 / 2 : ℝ≥0∞) ^ r * + (cond fairCoin (observedEvent e O P)) {X | π.transcript X v.length = v} := by + rw [transcriptEvent_eq_observedEvent e O π v q hq] + exact cond_observed_inter_affine e he D O P (transcriptPredicate v q) y hD + +end Klr.FiniteStage diff --git a/LeanPool/KLRandomness/FutureNoDrop.lean b/LeanPool/KLRandomness/FutureNoDrop.lean new file mode 100644 index 0000000000..8c6410101c --- /dev/null +++ b/LeanPool/KLRandomness/FutureNoDrop.lean @@ -0,0 +1,362 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.BlockProduct +import Mathlib.Tactic.Push + +/-! +# No-drop restrictions for the infinite block law + +The infinite block law and stage `j` agree on every Borel transcript event +restricted to paths on which no block `k ≥ j` ever loses full unread rank. +The proof derives equality on finite surviving transcript partitions, passes +to a decreasing intersection, and uses uniqueness on the cylinder generator. +The restrictions are not normalized, so zero-mass no-drop events are included. +-/ + +@[expose] public section + +namespace Klr.FutureNoDrop + +open MeasureTheory ProbabilityTheory StoppingTranscript +open scoped ENNReal + +/-- Every block not yet imposed at stage `j` retains full unread rank. -/ +def Safe (B : ℕ → AffineBlock) (j : ℕ) (π : ScanRule) (v : List Bool) : Prop := + ∀ k, j ≤ k → (B k).UnreadFullRank π v + +/-- No future block has lost full rank after `n` observed answers. -/ +def survivalEvent (B : ℕ → AffineBlock) (j : ℕ) (π : ScanRule) (n : ℕ) : Set Cantor := + {X | Safe B j π (π.transcript X n)} + +/-- No future block ever loses full unread rank, as an event of inputs. -/ +def noDropEvent (B : ℕ → AffineBlock) (j : ℕ) (π : ScanRule) : Set Cantor := + {X | ∀ n, Safe B j π (π.transcript X n)} + +/-- No future block ever loses full unread rank, as an event of infinite transcripts. -/ +def noDropTranscripts (B : ℕ → AffineBlock) (j : ℕ) (π : ScanRule) : Set Cantor := + {Y | ∀ n, Safe B j π (ScanRule.inputPrefix Y n)} + +theorem survivalEvent_antitone (B : ℕ → AffineBlock) (j : ℕ) (π : ScanRule) : + Antitone (survivalEvent B j π) := by + intro m n h X hX k hk + exact NoDrop.survivalEvent_antitone (B k) π h (hX k hk) + +theorem noDropEvent_eq_iInter (B : ℕ → AffineBlock) (j : ℕ) (π : ScanRule) : + noDropEvent B j π = ⋂ n, survivalEvent B j π n := by + ext X + simp [noDropEvent, survivalEvent] + +theorem noDropEvent_eq_iInter_blocks (B : ℕ → AffineBlock) (j : ℕ) (π : ScanRule) : + noDropEvent B j π = ⋂ k : {k : ℕ // j ≤ k}, NoDrop.noDropEvent (B k.val) π := by + ext X + simp only [noDropEvent, Safe, NoDrop.noDropEvent, Set.mem_ofPred_eq, Set.mem_iInter] + exact ⟨fun h k n => h n k.val k.property, fun h n k hk => h ⟨k, hk⟩ n⟩ + +theorem measurableSet_noDropEvent (B : ℕ → AffineBlock) (j : ℕ) (π : ScanRule) : + MeasurableSet (noDropEvent B j π) := by + rw [noDropEvent_eq_iInter_blocks] + exact MeasurableSet.iInter (fun k => NoDrop.measurableSet_noDropEvent (B k.val) π) + +theorem measurableSet_noDropTranscripts (B : ℕ → AffineBlock) (j : ℕ) (π : ScanRule) : + MeasurableSet (noDropTranscripts B j π) := by + change MeasurableSet {Y | ∀ n, Safe B j π (ScanRule.inputPrefix Y n)} + simp only [Set.ofPred_forall] + exact MeasurableSet.iInter (fun n => measurableSet_prefix_event (Safe B j π) n) + +theorem observationMap_preimage_noDropTranscripts (B : ℕ → AffineBlock) (j : ℕ) + (π : ScanRule) : + π.observationMap ⁻¹' noDropTranscripts B j π = noDropEvent B j π := by + ext X + simp only [Set.mem_preimage, noDropTranscripts, noDropEvent, Set.mem_ofPred_eq, + π.inputPrefix_observationMap] + +/-- The event is exactly absence of every finite strict rank drop in any future block. -/ +theorem mem_noDropEvent_iff_no_strict_rank_drop (B : ℕ → AffineBlock) (j : ℕ) + (π : ScanRule) (X : Cantor) : + X ∈ noDropEvent B j π ↔ ∀ k, j ≤ k → ∀ n, + ¬(B k).remainingRank π (π.transcript X (n + 1)) < + (B k).remainingRank π (π.transcript X n) := by + rw [noDropEvent_eq_iInter_blocks] + simp only [Set.mem_iInter, NoDrop.mem_noDropEvent_iff_no_strict_rank_drop] + exact ⟨fun h k hk => h ⟨k, hk⟩, fun h k => h k.val k.property⟩ + +/-- Length-`n` extensions whose unread columns remain full rank on every future block. -/ +def survivingExtensions (B : ℕ → AffineBlock) (j : ℕ) (π : ScanRule) + (v : List Bool) (n : ℕ) : Set (List Bool) := + {w | w.length = n ∧ v <+: w ∧ Safe B j π w} + +theorem survivingExtensions_prefixFree (B : ℕ → AffineBlock) (j : ℕ) (π : ScanRule) + (v : List Bool) (n : ℕ) : PrefixFree (survivingExtensions B j π v n) := by + intro u w hu hw h + exact h.eq_of_length (hu.1.trans hw.1.symm) + +theorem inputEvent_inter_survival_eq_union (B : ℕ → AffineBlock) (j : ℕ) (π : ScanRule) + (v : List Bool) (n : ℕ) (hn : v.length ≤ n) : + inputEvent π v ∩ survivalEvent B j π n = + unionEvent π (survivingExtensions B j π v n) := by + ext X + constructor + · rintro ⟨hv, hfull⟩ + change π.transcript X v.length = v at hv + have hw : π.transcript X n ∈ survivingExtensions B j π v n := by + refine ⟨π.length_transcript X n, ?_, hfull⟩ + simpa only [hv] using π.transcript_prefix X hn + apply Set.mem_iUnion.mpr + refine ⟨⟨π.transcript X n, hw⟩, ?_⟩ + change π.transcript X (π.transcript X n).length = π.transcript X n + rw [π.length_transcript] + · intro h + obtain ⟨w, hw⟩ := Set.mem_iUnion.mp h + refine ⟨inputEvent_subset_of_prefix π w.property.2.1 hw, ?_⟩ + change π.transcript X w.val.length = w.val at hw + rw [w.property.1] at hw + change Safe B j π (π.transcript X n) + rw [hw] + exact w.property.2.2 + +theorem measurableSet_survivalEvent (B : ℕ → AffineBlock) (j : ℕ) (π : ScanRule) + (n : ℕ) : MeasurableSet (survivalEvent B j π n) := by + have h := inputEvent_inter_survival_eq_union B j π [] n (by simp) + have he : inputEvent π [] = Set.univ := by + ext X + simp [inputEvent] + rw [he, Set.univ_inter] at h + rw [h] + exact measurableSet_unionEvent π _ + +theorem law_inputEvent_inter_survival (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) + (j : ℕ) (π : ScanRule) (v : List Bool) (n : ℕ) (hn : v.length ≤ n) : + BlockProduct.law B hdis (inputEvent π v ∩ survivalEvent B j π n) = + PrefixStage.law B j (inputEvent π v ∩ survivalEvent B j π n) := by + rw [inputEvent_inter_survival_eq_union B j π v n hn] + exact BlockProduct.law_unionEvent_eq_of_fullRank B hdis j π + (survivingExtensions_prefixFree B j π v n) (fun _ hw => hw.2.2) + +theorem inputEvent_inter_noDrop_eq_iInter (B : ℕ → AffineBlock) (j : ℕ) (π : ScanRule) + (v : List Bool) : + inputEvent π v ∩ noDropEvent B j π = + ⋂ n, inputEvent π v ∩ survivalEvent B j π (n + v.length) := by + ext X + constructor + · rintro ⟨hv, hfull⟩ + exact Set.mem_iInter.mpr (fun n => ⟨hv, hfull _⟩) + · intro h + have h' := Set.mem_iInter.mp h + refine ⟨(h' 0).1, ?_⟩ + intro n + exact survivalEvent_antitone B j π (Nat.le_add_right n v.length) (h' n).2 + +/-- Equality survives the decreasing limit to paths with no future rank drop. -/ +theorem law_inputEvent_inter_noDrop (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) + (j : ℕ) (π : ScanRule) (v : List Bool) : + BlockProduct.law B hdis (inputEvent π v ∩ noDropEvent B j π) = + PrefixStage.law B j (inputEvent π v ∩ noDropEvent B j π) := by + have ha : Antitone (fun n => inputEvent π v ∩ survivalEvent B j π (n + v.length)) := by + intro m n h X hX + exact ⟨hX.1, survivalEvent_antitone B j π (Nat.add_le_add_right h _) hX.2⟩ + have hm (n : ℕ) : MeasurableSet (inputEvent π v ∩ survivalEvent B j π (n + v.length)) := + (measurableSet_inputEvent π v).inter (measurableSet_survivalEvent B j π _) + let : IsProbabilityMeasure (PrefixStage.law B j) := PrefixStage.law_isProbabilityMeasure B hdis j + rw [inputEvent_inter_noDrop_eq_iInter, + ha.measure_iInter (fun n => (hm n).nullMeasurableSet) ⟨0, measure_ne_top _ _⟩, + ha.measure_iInter (fun n => (hm n).nullMeasurableSet) ⟨0, measure_ne_top _ _⟩] + exact iInf_congr fun n => law_inputEvent_inter_survival B hdis j π v + (n + v.length) (Nat.le_add_left _ _) + +/-- The actual infinite and stage-`j` transcript laws have identical no-future-drop restrictions. -/ +theorem law_map_restrict_noDrop (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) + (j : ℕ) (π : ScanRule) : + ((BlockProduct.law B hdis).map π.observationMap).restrict (noDropTranscripts B j π) = + ((PrefixStage.law B j).map π.observationMap).restrict (noDropTranscripts B j π) := by + apply measure_eq_of_cylinders + intro v + have hm := (measurableSet_cylinder v).inter (measurableSet_noDropTranscripts B j π) + rw [Measure.restrict_apply (measurableSet_cylinder v), + Measure.restrict_apply (measurableSet_cylinder v), + Measure.map_apply π.measurable_observationMap hm, + Measure.map_apply π.measurable_observationMap hm, + Set.preimage_inter, π.observationMap_preimage_cylinder, + observationMap_preimage_noDropTranscripts] + exact law_inputEvent_inter_noDrop B hdis j π v + +/-- Equality for every Borel transcript event on paths without a rank drop in any block `k ≥ j`. -/ +theorem law_noDrop_borel (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) + (j : ℕ) (π : ScanRule) {F : Set Cantor} (hF : MeasurableSet F) : + BlockProduct.law B hdis (π.observationMap ⁻¹' F ∩ noDropEvent B j π) = + PrefixStage.law B j (π.observationMap ⁻¹' F ∩ noDropEvent B j π) := by + have h := congrArg (fun μ : Measure Cantor => μ F) (law_map_restrict_noDrop B hdis j π) + rw [Measure.restrict_apply hF, Measure.restrict_apply hF, + Measure.map_apply π.measurable_observationMap + (hF.inter (measurableSet_noDropTranscripts B j π)), + Measure.map_apply π.measurable_observationMap + (hF.inter (measurableSet_noDropTranscripts B j π)), + Set.preimage_inter, observationMap_preimage_noDropTranscripts] at h + exact h + +theorem law_survivalEvent (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) + (j : ℕ) (π : ScanRule) (N : ℕ) : + BlockProduct.law B hdis (survivalEvent B j π N) = + PrefixStage.law B j (survivalEvent B j π N) := by + simpa [inputEvent] using law_inputEvent_inter_survival B hdis j π [] N (by simp) + +theorem law_noDropEvent (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) + (j : ℕ) (π : ScanRule) : + BlockProduct.law B hdis (noDropEvent B j π) = + PrefixStage.law B j (noDropEvent B j π) := by + simpa using law_noDrop_borel B hdis j π MeasurableSet.univ + +theorem noDropEvent_subset_survivalEvent (B : ℕ → AffineBlock) (j : ℕ) + (π : ScanRule) (N : ℕ) : noDropEvent B j π ⊆ survivalEvent B j π N := + fun _ h => h N + +/-- The first rank drop on any future block occurs after horizon `N`, at a finite query. -/ +def firstDropAfter (B : ℕ → AffineBlock) (j : ℕ) (π : ScanRule) (N : ℕ) : Set Cantor := + survivalEvent B j π N \ noDropEvent B j π + +theorem measurableSet_firstDropAfter (B : ℕ → AffineBlock) (j : ℕ) + (π : ScanRule) (N : ℕ) : MeasurableSet (firstDropAfter B j π N) := + (measurableSet_survivalEvent B j π N).diff (measurableSet_noDropEvent B j π) + +/-- The stopping tail has the paper's one-based query interpretation. Every future +block is still full rank at `N`, and some future block has a strict decrease at a later query. -/ +theorem mem_firstDropAfter_iff (B : ℕ → AffineBlock) (j : ℕ) + (π : ScanRule) (N : ℕ) (X : Cantor) : + X ∈ firstDropAfter B j π N ↔ + Safe B j π (π.transcript X N) ∧ ∃ k, j ≤ k ∧ ∃ t, N < t ∧ + (B k).remainingRank π (π.transcript X t) < + (B k).remainingRank π (π.transcript X (t - 1)) := by + classical + constructor + · rintro ⟨hN, hno⟩ + rw [mem_noDropEvent_iff_no_strict_rank_drop] at hno + push Not at hno + obtain ⟨k, hk, n, hdrop⟩ := hno + refine ⟨hN, k, hk, n + 1, ?_, by simpa using hdrop⟩ + by_contra h + have hnN : n + 1 ≤ N := by omega + have hn1 := survivalEvent_antitone B j π hnN hN k hk + have hn0 := survivalEvent_antitone B j π (show n ≤ N by omega) hN k hk + rw [(B k).unreadFullRank_iff_remainingRank] at hn1 hn0 + rw [hn1, hn0] at hdrop + exact lt_irrefl _ hdrop + · rintro ⟨hN, k, hk, t, ht, hdrop⟩ + refine ⟨hN, ?_⟩ + intro hno + have h := (mem_noDropEvent_iff_no_strict_rank_drop B j π X).mp hno k hk (t - 1) + have ht1 : 1 ≤ t := by omega + rw [Nat.sub_add_cancel ht1] at h + exact h hdrop + +/-- The infinite and finite-stage laws agree on the first-future-drop tail. -/ +theorem law_firstDropAfter (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) + (j : ℕ) (π : ScanRule) (N : ℕ) : + BlockProduct.law B hdis (firstDropAfter B j π N) = + PrefixStage.law B j (firstDropAfter B j π N) := by + let : IsProbabilityMeasure (PrefixStage.law B j) := PrefixStage.law_isProbabilityMeasure B hdis j + rw [firstDropAfter, + measure_sdiff (noDropEvent_subset_survivalEvent B j π N) + (measurableSet_noDropEvent B j π).nullMeasurableSet (measure_ne_top _ _), + measure_sdiff (noDropEvent_subset_survivalEvent B j π N) + (measurableSet_noDropEvent B j π).nullMeasurableSet (measure_ne_top _ _), + law_survivalEvent B hdis j π N, law_noDropEvent B hdis j π] + +/-- The safety cutoff may precede the comparison stage: retaining full rank on all +blocks `k ≥ j` in particular retains it on every not-yet-imposed block `k ≥ n`. -/ +theorem law_inputEvent_inter_survival_of_le (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) + (j n : ℕ) (hjn : j ≤ n) (π : ScanRule) (v : List Bool) (N : ℕ) + (hN : v.length ≤ N) : + BlockProduct.law B hdis (inputEvent π v ∩ survivalEvent B j π N) = + PrefixStage.law B n (inputEvent π v ∩ survivalEvent B j π N) := by + rw [inputEvent_inter_survival_eq_union B j π v N hN] + apply BlockProduct.law_unionEvent_eq_of_fullRank B hdis n π + (survivingExtensions_prefixFree B j π v N) + intro w hw k hk + exact hw.2.2 k (hjn.trans hk) + +theorem law_inputEvent_inter_noDrop_of_le (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) + (j n : ℕ) (hjn : j ≤ n) (π : ScanRule) (v : List Bool) : + BlockProduct.law B hdis (inputEvent π v ∩ noDropEvent B j π) = + PrefixStage.law B n (inputEvent π v ∩ noDropEvent B j π) := by + have ha : Antitone (fun N => inputEvent π v ∩ survivalEvent B j π (N + v.length)) := by + intro a b h X hX + exact ⟨hX.1, survivalEvent_antitone B j π (Nat.add_le_add_right h _) hX.2⟩ + have hm (N : ℕ) : MeasurableSet (inputEvent π v ∩ survivalEvent B j π (N + v.length)) := + (measurableSet_inputEvent π v).inter (measurableSet_survivalEvent B j π _) + let : IsProbabilityMeasure (PrefixStage.law B n) := PrefixStage.law_isProbabilityMeasure B hdis n + rw [inputEvent_inter_noDrop_eq_iInter, + ha.measure_iInter (fun N => (hm N).nullMeasurableSet) ⟨0, measure_ne_top _ _⟩, + ha.measure_iInter (fun N => (hm N).nullMeasurableSet) ⟨0, measure_ne_top _ _⟩] + exact iInf_congr fun N => law_inputEvent_inter_survival_of_le B hdis j n hjn π v + (N + v.length) (Nat.le_add_left _ _) + +/-- General no-drop restriction equality with a safety cutoff `j` and any stage `n ≥ j`. -/ +theorem law_map_restrict_noDrop_of_le (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) + (j n : ℕ) (hjn : j ≤ n) (π : ScanRule) : + ((BlockProduct.law B hdis).map π.observationMap).restrict (noDropTranscripts B j π) = + ((PrefixStage.law B n).map π.observationMap).restrict (noDropTranscripts B j π) := by + apply measure_eq_of_cylinders + intro v + have hm := (measurableSet_cylinder v).inter (measurableSet_noDropTranscripts B j π) + rw [Measure.restrict_apply (measurableSet_cylinder v), + Measure.restrict_apply (measurableSet_cylinder v), + Measure.map_apply π.measurable_observationMap hm, + Measure.map_apply π.measurable_observationMap hm, + Set.preimage_inter, π.observationMap_preimage_cylinder, + observationMap_preimage_noDropTranscripts] + exact law_inputEvent_inter_noDrop_of_le B hdis j n hjn π v + +theorem law_noDrop_borel_of_le (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) + (j n : ℕ) (hjn : j ≤ n) (π : ScanRule) {F : Set Cantor} (hF : MeasurableSet F) : + BlockProduct.law B hdis (π.observationMap ⁻¹' F ∩ noDropEvent B j π) = + PrefixStage.law B n (π.observationMap ⁻¹' F ∩ noDropEvent B j π) := by + have h := congrArg (fun μ : Measure Cantor => μ F) + (law_map_restrict_noDrop_of_le B hdis j n hjn π) + rw [Measure.restrict_apply hF, Measure.restrict_apply hF, + Measure.map_apply π.measurable_observationMap + (hF.inter (measurableSet_noDropTranscripts B j π)), + Measure.map_apply π.measurable_observationMap + (hF.inter (measurableSet_noDropTranscripts B j π)), + Set.preimage_inter, observationMap_preimage_noDropTranscripts] at h + exact h + +/-- The first-future-drop tail can be compared with a stage that already contains +the first of the tracked blocks. The case `n = j + 1` is the Section 6 comparison. -/ +theorem law_firstDropAfter_of_le (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) + (j n : ℕ) (hjn : j ≤ n) (π : ScanRule) (N : ℕ) : + BlockProduct.law B hdis (firstDropAfter B j π N) = + PrefixStage.law B n (firstDropAfter B j π N) := by + have hs : BlockProduct.law B hdis (survivalEvent B j π N) = + PrefixStage.law B n (survivalEvent B j π N) := by + simpa [inputEvent] using + law_inputEvent_inter_survival_of_le B hdis j n hjn π [] N (by simp) + have hd : BlockProduct.law B hdis (noDropEvent B j π) = + PrefixStage.law B n (noDropEvent B j π) := by + simpa using law_noDrop_borel_of_le B hdis j n hjn π MeasurableSet.univ + let : IsProbabilityMeasure (PrefixStage.law B n) := PrefixStage.law_isProbabilityMeasure B hdis n + rw [firstDropAfter, + measure_sdiff (noDropEvent_subset_survivalEvent B j π N) + (measurableSet_noDropEvent B j π).nullMeasurableSet (measure_ne_top _ _), + measure_sdiff (noDropEvent_subset_survivalEvent B j π N) + (measurableSet_noDropEvent B j π).nullMeasurableSet (measure_ne_top _ _), hs, hd] + +end Klr.FutureNoDrop diff --git a/LeanPool/KLRandomness/HorizonAvoidance.lean b/LeanPool/KLRandomness/HorizonAvoidance.lean new file mode 100644 index 0000000000..221a7b8aab --- /dev/null +++ b/LeanPool/KLRandomness/HorizonAvoidance.lean @@ -0,0 +1,166 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.AffineAnswer +public import Mathlib.Data.List.OfFn + +/-! +# A finite avoidance set for every branch up to a query horizon + +The first `N` queries are chosen from transcripts of lengths strictly less than +`N`. We enumerate those transcripts explicitly as the finite type +`Σ t : Fin N, (Fin t.val → Bool)` and apply the scan rule to each word. +Consequently a block outside this finite set has no observed coordinates on +any transcript of length at most `N`, and retains full unread rank there. + +Finite unions handle finitely many scan rules with individual horizons. The +corresponding numerical bounds allow later supports to be chosen above every +position that must be avoided. +-/ + +@[expose] public section + +namespace Klr.HorizonAvoidance + +open AffineObservation + +/-- All positions a scan can query among its first `N` queries, over every branch. -/ +def queryPositions (π : ScanRule) (N : ℕ) : Finset ℕ := + Finset.univ.image (fun p : Σ t : Fin N, (Fin t.val → Bool) => π.query (List.ofFn p.2)) + +/-- The explicit enumeration contains exactly the queries from all shorter transcripts. -/ +theorem mem_queryPositions (π : ScanRule) (N q : ℕ) : + q ∈ queryPositions π N ↔ ∃ v : List Bool, v.length < N ∧ π.query v = q := by + constructor + · intro h + obtain ⟨p, _, hp⟩ := Finset.mem_image.mp h + exact ⟨List.ofFn p.2, by rw [List.length_ofFn]; exact p.1.isLt, hp⟩ + · rintro ⟨v, hv, rfl⟩ + refine Finset.mem_image.mpr ⟨⟨⟨v.length, hv⟩, v.get⟩, Finset.mem_univ _, ?_⟩ + simp [List.ofFn_get] + +@[simp] theorem queryPositions_zero (π : ScanRule) : queryPositions π 0 = ∅ := by + ext q + simp [mem_queryPositions] + +theorem query_mem_queryPositions (π : ScanRule) (N : ℕ) (v : List Bool) + (hv : v.length < N) : π.query v ∈ queryPositions π N := + (mem_queryPositions π N _).mpr ⟨v, hv, rfl⟩ + +theorem queryPositions_mono (π : ScanRule) : Monotone (queryPositions π) := by + intro N M hNM q hq + obtain ⟨v, hv, hvq⟩ := (mem_queryPositions π N q).mp hq + exact (mem_queryPositions π M q).mpr ⟨v, lt_of_lt_of_le hv hNM, hvq⟩ + +/-- Every position read along a transcript of length at most `N` is in the avoidance set. -/ +theorem queriedPositions_subset (π : ScanRule) (N : ℕ) {v : List Bool} + (hv : v.length ≤ N) : π.queriedPositions v ⊆ queryPositions π N := by + intro q hq + obtain ⟨i, _, rfl⟩ := Finset.mem_image.mp hq + exact query_mem_queryPositions π N (v.take i.val) + (lt_of_le_of_lt (List.length_take_le _ _) (lt_of_lt_of_le i.isLt hv)) + +/-- An explicit strict upper bound for every coordinate queried before horizon `N`. -/ +def queryBound (π : ScanRule) (N : ℕ) : ℕ := (queryPositions π N).sup id + 1 + +theorem lt_queryBound_of_mem (π : ScanRule) (N : ℕ) {q : ℕ} + (hq : q ∈ queryPositions π N) : q < queryBound π N := + Nat.lt_succ_of_le (Finset.le_sup (f := id) hq) + +theorem query_lt_queryBound (π : ScanRule) (N : ℕ) (v : List Bool) (hv : v.length < N) : + π.query v < queryBound π N := + lt_queryBound_of_mem π N (query_mem_queryPositions π N v hv) + +/-- Any finite support above the bound is disjoint from the all-branch avoidance set. -/ +theorem disjoint_of_queryBound_le (π : ScanRule) (N : ℕ) (S : Finset ℕ) + (hS : ∀ q ∈ S, queryBound π N ≤ q) : Disjoint (queryPositions π N) S := by + apply Finset.disjoint_left.mpr + intro q hq hqS + exact (not_lt_of_ge (hS q hqS)) (lt_queryBound_of_mem π N hq) + +/-- A block with no queried coordinate retains its full initial row rank. -/ +theorem unreadFullRank_of_disjoint_queriedPositions (B : AffineBlock) (π : ScanRule) + (v : List Bool) (hdis : Disjoint (π.queriedPositions v) B.support) : + B.UnreadFullRank π v := by + intro y + obtain ⟨x, hx⟩ := B.fullRank y + refine ⟨fun i => x i.val, ?_⟩ + change B.matrix (extendUnread (B.observed π v) (fun i => x i.val)) = y + have he : extendUnread (B.observed π v) (fun i => x i.val) = x := by + funext i + have hi : i ∉ B.observed π v := fun h => Finset.disjoint_left.mp hdis h i.property + simp [extendUnread, hi] + rw [he, hx] + +/-- Avoiding the explicit finite set preserves full unread rank on every branch +through the horizon, including the transcript after exactly `N` answers. -/ +theorem unreadFullRank_of_disjoint (B : AffineBlock) (π : ScanRule) (N : ℕ) + (hdis : Disjoint (queryPositions π N) B.support) + (v : List Bool) (hv : v.length ≤ N) : B.UnreadFullRank π v := + unreadFullRank_of_disjoint_queriedPositions B π v + (hdis.mono_left (queriedPositions_subset π N hv)) + +theorem unreadFullRank_of_queryBound_le (B : AffineBlock) (π : ScanRule) (N : ℕ) + (hB : ∀ q ∈ B.support, queryBound π N ≤ q) + (v : List Bool) (hv : v.length ≤ N) : B.UnreadFullRank π v := + unreadFullRank_of_disjoint B π N (disjoint_of_queryBound_le π N B.support hB) v hv + +/-- A finite collection of scans may have different finite horizons. -/ +def familyPositions {ι : Type*} [Fintype ι] (π : ι → ScanRule) (N : ι → ℕ) : Finset ℕ := + Finset.univ.biUnion (fun i => queryPositions (π i) (N i)) + +theorem queryPositions_subset_familyPositions {ι : Type*} [Fintype ι] + (π : ι → ScanRule) (N : ι → ℕ) (i : ι) : + queryPositions (π i) (N i) ⊆ familyPositions π N := by + intro q hq + exact Finset.mem_biUnion.mpr ⟨i, Finset.mem_univ _, hq⟩ + +theorem queriedPositions_subset_familyPositions {ι : Type*} [Fintype ι] + (π : ι → ScanRule) (N : ι → ℕ) (i : ι) {v : List Bool} (hv : v.length ≤ N i) : + (π i).queriedPositions v ⊆ familyPositions π N := + (queriedPositions_subset (π i) (N i) hv).trans (queryPositions_subset_familyPositions π N i) + +/-- One finite bound works simultaneously for every scan in the finite family. -/ +def familyBound {ι : Type*} [Fintype ι] (π : ι → ScanRule) (N : ι → ℕ) : ℕ := + (familyPositions π N).sup id + 1 + +theorem lt_familyBound_of_mem {ι : Type*} [Fintype ι] + (π : ι → ScanRule) (N : ι → ℕ) {q : ℕ} (hq : q ∈ familyPositions π N) : + q < familyBound π N := Nat.lt_succ_of_le (Finset.le_sup (f := id) hq) + +theorem query_lt_familyBound {ι : Type*} [Fintype ι] + (π : ι → ScanRule) (N : ι → ℕ) (i : ι) (v : List Bool) (hv : v.length < N i) : + (π i).query v < familyBound π N := + lt_familyBound_of_mem π N + (queryPositions_subset_familyPositions π N i (query_mem_queryPositions (π i) (N i) v hv)) + +theorem disjoint_of_familyBound_le {ι : Type*} [Fintype ι] + (π : ι → ScanRule) (N : ι → ℕ) (S : Finset ℕ) + (hS : ∀ q ∈ S, familyBound π N ≤ q) : Disjoint (familyPositions π N) S := by + apply Finset.disjoint_left.mpr + intro q hq hqS + exact (not_lt_of_ge (hS q hqS)) (lt_familyBound_of_mem π N hq) + +/-- Avoiding the finite union guarantees full unread rank for every scan through +its assigned horizon, on every possible transcript. -/ +theorem family_unreadFullRank_of_disjoint {ι : Type*} [Fintype ι] + (B : AffineBlock) (π : ι → ScanRule) (N : ι → ℕ) + (hdis : Disjoint (familyPositions π N) B.support) + (i : ι) (v : List Bool) (hv : v.length ≤ N i) : B.UnreadFullRank (π i) v := + unreadFullRank_of_disjoint_queriedPositions B (π i) v + (hdis.mono_left (queriedPositions_subset_familyPositions π N i hv)) + +theorem family_unreadFullRank_of_bound_le {ι : Type*} [Fintype ι] + (B : AffineBlock) (π : ι → ScanRule) (N : ι → ℕ) + (hB : ∀ q ∈ B.support, familyBound π N ≤ q) + (i : ι) (v : List Bool) (hv : v.length ≤ N i) : B.UnreadFullRank (π i) v := + family_unreadFullRank_of_disjoint B π N (disjoint_of_familyBound_le π N B.support hB) i v hv + +end Klr.HorizonAvoidance diff --git a/LeanPool/KLRandomness/HorizonLaw.lean b/LeanPool/KLRandomness/HorizonLaw.lean new file mode 100644 index 0000000000..c2044f2e00 --- /dev/null +++ b/LeanPool/KLRandomness/HorizonLaw.lean @@ -0,0 +1,203 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.BlockProduct +public import LeanPool.KLRandomness.EarlyLateWagers +public import Mathlib.MeasureTheory.Integral.Bochner.Basic +import Mathlib.Tactic.Measurability + +/-! +# Finite-horizon expectations under the infinite block law + +If every block not yet imposed has full unread rank after every transcript of a +fixed length, the infinite block law has exactly the same finite-answer +distribution as the current finite stage. Consequently every functional of +those answers has the same expectation under the two laws. + +The final theorem applies this equality to the early rank-drop wager sum in +Section 6. Its horizon dependence is proved directly from the definitions; no +distributional or expectation-transfer premise is assumed. +-/ + +@[expose] public section + +namespace Klr.HorizonLaw + +open MeasureTheory StoppingTranscript +open scoped ENNReal + +/-- The finite answer vector of a total scan, with a fixed finite codomain. -/ +def prefixAnswers (π : ScanRule) (N : ℕ) (X : Cantor) : Fin N → Bool := + fun i => (π.transcript X N).getD i.val false + +theorem measurable_prefixAnswers (π : ScanRule) (N : ℕ) : + Measurable (prefixAnswers π N) := + Measurable.of_eval fun i => + DropEvents.measurable_transcript_eval π N (fun v => v.getD i.val false) + +@[simp] theorem ofFn_prefixAnswers (π : ScanRule) (N : ℕ) (X : Cantor) : + List.ofFn (prefixAnswers π N X) = π.transcript X N := by + apply List.ext_getElem (by simp) + intro i hi hj + simp only [List.getElem_ofFn, prefixAnswers] + exact List.getD_eq_getElem _ _ hj + +theorem prefixAnswers_preimage_singleton (π : ScanRule) (N : ℕ) + (a : Fin N → Bool) : + prefixAnswers π N ⁻¹' {a} = inputEvent π (List.ofFn a) := by + ext X + change prefixAnswers π N X = a ↔ + π.transcript X (List.ofFn a).length = List.ofFn a + rw [List.length_ofFn, ← ofFn_prefixAnswers π N X, List.ofFn_inj] + +/-- Equality of the complete finite-answer distributions. -/ +theorem map_prefixAnswers_eq_stage (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) + (n : ℕ) (π : ScanRule) (N : ℕ) + (hfull : ∀ v, v.length = N → ∀ k, n ≤ k → (B k).UnreadFullRank π v) : + (BlockProduct.law B hdis).map (prefixAnswers π N) = + (PrefixStage.law B n).map (prefixAnswers π N) := by + apply Measure.ext_of_singleton + intro a + rw [Measure.map_apply (measurable_prefixAnswers π N) (measurableSet_singleton a), + Measure.map_apply (measurable_prefixAnswers π N) (measurableSet_singleton a), + prefixAnswers_preimage_singleton] + exact BlockProduct.law_inputEvent_eq_of_fullRank B hdis n π (List.ofFn a) + (hfull _ List.length_ofFn) + +/-- Every nonnegative functional of the finite answer vector has the same integral. -/ +theorem lintegral_prefixAnswers_eq_stage (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) + (n : ℕ) (π : ScanRule) (N : ℕ) + (hfull : ∀ v, v.length = N → ∀ k, n ≤ k → (B k).UnreadFullRank π v) + (f : (Fin N → Bool) → ℝ≥0∞) : + ∫⁻ X, f (prefixAnswers π N X) ∂BlockProduct.law B hdis = + ∫⁻ X, f (prefixAnswers π N X) ∂PrefixStage.law B n := by + rw [← lintegral_map (measurable_of_countable f) (measurable_prefixAnswers π N), + ← lintegral_map (measurable_of_countable f) (measurable_prefixAnswers π N), + map_prefixAnswers_eq_stage B hdis n π N hfull] + +/-- The corresponding real-valued integral identity. -/ +theorem integral_prefixAnswers_eq_stage (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) + (n : ℕ) (π : ScanRule) (N : ℕ) + (hfull : ∀ v, v.length = N → ∀ k, n ≤ k → (B k).UnreadFullRank π v) + (f : (Fin N → Bool) → ℝ) : + ∫ X, f (prefixAnswers π N X) ∂BlockProduct.law B hdis = + ∫ X, f (prefixAnswers π N X) ∂PrefixStage.law B n := by + rw [← integral_map_of_stronglyMeasurable (measurable_prefixAnswers π N) + (StronglyMeasurable.of_discrete (f := f)), + ← integral_map_of_stronglyMeasurable (measurable_prefixAnswers π N) + (StronglyMeasurable.of_discrete (f := f)), + map_prefixAnswers_eq_stage B hdis n π N hfull] + +/-- A word functional needs no independent measurability assumption: only finitely +many length-`N` words can occur. -/ +theorem lintegral_transcript_eq_stage (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) + (n : ℕ) (π : ScanRule) (N : ℕ) + (hfull : ∀ v, v.length = N → ∀ k, n ≤ k → (B k).UnreadFullRank π v) + (f : List Bool → ℝ≥0∞) : + ∫⁻ X, f (π.transcript X N) ∂BlockProduct.law B hdis = + ∫⁻ X, f (π.transcript X N) ∂PrefixStage.law B n := by + simpa only [ofFn_prefixAnswers] using + lintegral_prefixAnswers_eq_stage B hdis n π N hfull (fun a => f (List.ofFn a)) + +theorem integral_transcript_eq_stage (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) + (n : ℕ) (π : ScanRule) (N : ℕ) + (hfull : ∀ v, v.length = N → ∀ k, n ≤ k → (B k).UnreadFullRank π v) + (f : List Bool → ℝ) : + ∫ X, f (π.transcript X N) ∂BlockProduct.law B hdis = + ∫ X, f (π.transcript X N) ∂PrefixStage.law B n := by + simpa only [ofFn_prefixAnswers] using + integral_prefixAnswers_eq_stage B hdis n π N hfull (fun a => f (List.ofFn a)) + +/-- Any function constant on equal horizon transcripts factors through the finite +answer vector, including values on unrealizable words. -/ +theorem factorsThrough_prefixAnswers {α : Type*} (π : ScanRule) (N : ℕ) + (g : Cantor → α) + (hg : ∀ X Y, π.transcript X N = π.transcript Y N → g X = g Y) : + Function.FactorsThrough g (prefixAnswers π N) := by + intro X Y h + apply hg X Y + simpa only [ofFn_prefixAnswers] using congrArg List.ofFn h + +/-- Equality of nonnegative integrals for any horizon-dependent input functional. -/ +theorem lintegral_eq_stage_of_transcript (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) + (n : ℕ) (π : ScanRule) (N : ℕ) + (hfull : ∀ v, v.length = N → ∀ k, n ≤ k → (B k).UnreadFullRank π v) + (g : Cantor → ℝ≥0∞) + (hg : ∀ X Y, π.transcript X N = π.transcript Y N → g X = g Y) : + ∫⁻ X, g X ∂BlockProduct.law B hdis = + ∫⁻ X, g X ∂PrefixStage.law B n := by + obtain ⟨f, rfl⟩ := (Function.factorsThrough_iff g).mp + (factorsThrough_prefixAnswers π N g hg) + exact lintegral_prefixAnswers_eq_stage B hdis n π N hfull f + +theorem integral_eq_stage_of_transcript (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) + (n : ℕ) (π : ScanRule) (N : ℕ) + (hfull : ∀ v, v.length = N → ∀ k, n ≤ k → (B k).UnreadFullRank π v) + (g : Cantor → ℝ) + (hg : ∀ X Y, π.transcript X N = π.transcript Y N → g X = g Y) : + ∫ X, g X ∂BlockProduct.law B hdis = + ∫ X, g X ∂PrefixStage.law B n := by + obtain ⟨f, rfl⟩ := (Function.factorsThrough_iff g).mp + (factorsThrough_prefixAnswers π N g hg) + exact integral_prefixAnswers_eq_stage B hdis n π N hfull f + +/-- The early wager sum is determined by the transcript at its prescribed horizon. -/ +theorem earlyWager_eq_of_transcript (B : ℕ → AffineBlock) (π : ScanRule) + (w : List Bool → ℝ) (V : ℕ → ℕ) (j : ℕ) (X Y : Cantor) + (h : π.transcript X (V j) = π.transcript Y (V j)) : + EarlyLateWagers.earlyWager B π w V j X = + EarlyLateWagers.earlyWager B π w V j Y := by + classical + unfold EarlyLateWagers.earlyWager + apply Finset.sum_congr rfl + intro t ht + have ht' : t ≤ V j := (Finset.mem_range.mp ht).le + have he : π.transcript X t = π.transcript Y t := by + calc + π.transcript X t = (π.transcript X (V j)).take t := + (π.transcript_take X ht').symm + _ = (π.transcript Y (V j)).take t := congrArg (List.take t) h + _ = π.transcript Y t := π.transcript_take Y ht' + simp only [EarlyLateWagers.blockWager, DropEvents.atTime, he] + rfl + +/-- The early expectation under the actual infinite law is exactly the expectation +after imposing block `j`, provided all later blocks preserve full rank through `V j`. -/ +theorem lintegral_earlyWager_eq_stage (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) + (π : ScanRule) (w : List Bool → ℝ) (V : ℕ → ℕ) (j : ℕ) + (havoid : ∀ v, v.length = V j → ∀ k, j < k → (B k).UnreadFullRank π v) : + ∫⁻ X, ENNReal.ofReal (EarlyLateWagers.earlyWager B π w V j X) + ∂BlockProduct.law B hdis = + ∫⁻ X, ENNReal.ofReal (EarlyLateWagers.earlyWager B π w V j X) + ∂PrefixStage.law B (j + 1) := by + apply lintegral_eq_stage_of_transcript B hdis (j + 1) π (V j) + (fun v hv k hk => havoid v hv k (Nat.lt_of_succ_le hk)) + intro X Y h + exact congrArg ENNReal.ofReal (earlyWager_eq_of_transcript B π w V j X Y h) + +theorem integral_earlyWager_eq_stage (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) + (π : ScanRule) (w : List Bool → ℝ) (V : ℕ → ℕ) (j : ℕ) + (havoid : ∀ v, v.length = V j → ∀ k, j < k → (B k).UnreadFullRank π v) : + ∫ X, EarlyLateWagers.earlyWager B π w V j X ∂BlockProduct.law B hdis = + ∫ X, EarlyLateWagers.earlyWager B π w V j X ∂PrefixStage.law B (j + 1) := by + exact integral_eq_stage_of_transcript B hdis (j + 1) π (V j) + (fun v hv k hk => havoid v hv k (Nat.lt_of_succ_le hk)) _ + (earlyWager_eq_of_transcript B π w V j) + +end Klr.HorizonLaw diff --git a/LeanPool/KLRandomness/Imports.lean b/LeanPool/KLRandomness/Imports.lean new file mode 100644 index 0000000000..6e4f67b87b --- /dev/null +++ b/LeanPool/KLRandomness/Imports.lean @@ -0,0 +1,156 @@ +/- +Copyright (c) 2026 Lean Pool contributors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Lean Pool contributors +-/ +module -- shake: keep-all --deprecated_module: ignore + +-- Generated project imports; run `lake exe mk_all`. +public import LeanPool.KLRandomness +public import LeanPool.KLRandomness.Affine +public import LeanPool.KLRandomness.AffineAnswer +public import LeanPool.KLRandomness.AffineAnswerAlgebra +public import LeanPool.KLRandomness.AffineAnswerMeasure +public import LeanPool.KLRandomness.AffineBlock +public import LeanPool.KLRandomness.AffineCode +public import LeanPool.KLRandomness.AffineCodeCoverage +public import LeanPool.KLRandomness.AffineCodePrefix +public import LeanPool.KLRandomness.AffineDescription +public import LeanPool.KLRandomness.AffineDescriptionSeparation +public import LeanPool.KLRandomness.AffineFamily +public import LeanPool.KLRandomness.AffineObservation +public import LeanPool.KLRandomness.AffineProgramLength +public import LeanPool.KLRandomness.BaseFour +public import LeanPool.KLRandomness.BaseInvariance +public import LeanPool.KLRandomness.Betting +public import LeanPool.KLRandomness.BlockProduct +public import LeanPool.KLRandomness.BlockProductAnswer +public import LeanPool.KLRandomness.BlockRandomness +public import LeanPool.KLRandomness.Cantor +public import LeanPool.KLRandomness.ComputableNonrandom +public import LeanPool.KLRandomness.ComputableRational +public import LeanPool.KLRandomness.ConfinedStageConstruction +public import LeanPool.KLRandomness.ConfinedStageRecursion +public import LeanPool.KLRandomness.DescriptionBudget +public import LeanPool.KLRandomness.DropEvents +public import LeanPool.KLRandomness.EarlyLateWagers +public import LeanPool.KLRandomness.EffectiveNormalization +public import LeanPool.KLRandomness.EffectiveNormalizationStrategy +public import LeanPool.KLRandomness.EffectiveOpen +public import LeanPool.KLRandomness.EffectiveScan +public import LeanPool.KLRandomness.EffectiveSearch +public import LeanPool.KLRandomness.FairForced +public import LeanPool.KLRandomness.FiniteMeasure +public import LeanPool.KLRandomness.FiniteProbability +public import LeanPool.KLRandomness.FiniteStage +public import LeanPool.KLRandomness.FutureNoDrop +public import LeanPool.KLRandomness.HorizonAvoidance +public import LeanPool.KLRandomness.HorizonLaw +public import LeanPool.KLRandomness.LateDropBound +public import LeanPool.KLRandomness.MLImpliesKL +public import LeanPool.KLRandomness.MartinLof +public import LeanPool.KLRandomness.MaximalInequality +public import LeanPool.KLRandomness.NoDrop +public import LeanPool.KLRandomness.Normalization +public import LeanPool.KLRandomness.NormalizationSuccess +public import LeanPool.KLRandomness.PairRespecting +public import LeanPool.KLRandomness.ParityConstruction +public import LeanPool.KLRandomness.ParityDescription +public import LeanPool.KLRandomness.ParityPools +public import LeanPool.KLRandomness.PartialBetting +public import LeanPool.KLRandomness.PartialBettingCapital +public import LeanPool.KLRandomness.PoolAcceptance +public import LeanPool.KLRandomness.PoolAdvice +public import LeanPool.KLRandomness.PoolAdviceComputable +public import LeanPool.KLRandomness.PoolAdviceMeasure +public import LeanPool.KLRandomness.PoolAdviceTables +public import LeanPool.KLRandomness.PoolApproximation +public import LeanPool.KLRandomness.PoolApproximationFunction +public import LeanPool.KLRandomness.PoolConstruction +public import LeanPool.KLRandomness.PoolCoverage +public import LeanPool.KLRandomness.PoolParameters +public import LeanPool.KLRandomness.PoolPartition +public import LeanPool.KLRandomness.PoolPartitionQuery +public import LeanPool.KLRandomness.PoolPartitionRepresentative +public import LeanPool.KLRandomness.PoolQuery +public import LeanPool.KLRandomness.PoolQueryLimit +public import LeanPool.KLRandomness.PoolSearch +public import LeanPool.KLRandomness.PoolSelection +public import LeanPool.KLRandomness.PoolSoundness +public import LeanPool.KLRandomness.PoolWeakLimit +public import LeanPool.KLRandomness.PoolWeighted +public import LeanPool.KLRandomness.PoolWitness +public import LeanPool.KLRandomness.PrefixStage +public import LeanPool.KLRandomness.RandomMatrix +public import LeanPool.KLRandomness.RandomMatrixAlgebra +public import LeanPool.KLRandomness.RemainingRank +public import LeanPool.KLRandomness.SampleConcentration +public import LeanPool.KLRandomness.ScanMeasure +public import LeanPool.KLRandomness.Separation +public import LeanPool.KLRandomness.Sparse +public import LeanPool.KLRandomness.SparseCandidate +public import LeanPool.KLRandomness.SparseCandidateCode +public import LeanPool.KLRandomness.SparseCandidateList +public import LeanPool.KLRandomness.SparseCandidateWeights +public import LeanPool.KLRandomness.SparseCodeCount +public import LeanPool.KLRandomness.SparseListCodeBridge +public import LeanPool.KLRandomness.SparseListConstruction +public import LeanPool.KLRandomness.SparseListSearch +public import LeanPool.KLRandomness.SparseListSearchComputable +public import LeanPool.KLRandomness.SparseListSearchEffective +public import LeanPool.KLRandomness.SparseListWeights +public import LeanPool.KLRandomness.SparseParameters +public import LeanPool.KLRandomness.SparseSearchMask +public import LeanPool.KLRandomness.SparseSearchRank +public import LeanPool.KLRandomness.Splitting +public import LeanPool.KLRandomness.SplittingClopen +public import LeanPool.KLRandomness.SplittingReserve +public import LeanPool.KLRandomness.SplittingScheduler +public import LeanPool.KLRandomness.SplittingWitness +public import LeanPool.KLRandomness.StageCandidate +public import LeanPool.KLRandomness.StageCandidateBridge +public import LeanPool.KLRandomness.StageCandidateCode +public import LeanPool.KLRandomness.StageChoice +public import LeanPool.KLRandomness.StageCodeSearch +public import LeanPool.KLRandomness.StageConditionalScan +public import LeanPool.KLRandomness.StageConstruction +public import LeanPool.KLRandomness.StageEnumeration +public import LeanPool.KLRandomness.StageErrorBudget +public import LeanPool.KLRandomness.StageEstimates +public import LeanPool.KLRandomness.StageFiniteCondition +public import LeanPool.KLRandomness.StageFiniteProbability +public import LeanPool.KLRandomness.StageFiniteScan +public import LeanPool.KLRandomness.StageFiniteWager +public import LeanPool.KLRandomness.StageHorizon +public import LeanPool.KLRandomness.StageHorizonChoice +public import LeanPool.KLRandomness.StageHorizonChoiceBounds +public import LeanPool.KLRandomness.StageHorizonComputable +public import LeanPool.KLRandomness.StageOneStep +public import LeanPool.KLRandomness.StageOneStepBounds +public import LeanPool.KLRandomness.StageOneStepDefs +public import LeanPool.KLRandomness.StageOneStepHorizon +public import LeanPool.KLRandomness.StagePreHorizon +public import LeanPool.KLRandomness.StagePrefixCode +public import LeanPool.KLRandomness.StagePrepared +public import LeanPool.KLRandomness.StagePreparedIndex +public import LeanPool.KLRandomness.StageProgramLength +public import LeanPool.KLRandomness.StageRank +public import LeanPool.KLRandomness.StageRankAverage +public import LeanPool.KLRandomness.StageRankCode +public import LeanPool.KLRandomness.StageRankLimit +public import LeanPool.KLRandomness.StageRankLimitMeasure +public import LeanPool.KLRandomness.StageRankProbability +public import LeanPool.KLRandomness.StageRankZero +public import LeanPool.KLRandomness.StageRationalError +public import LeanPool.KLRandomness.StageReconstruction +public import LeanPool.KLRandomness.StageRecursion +public import LeanPool.KLRandomness.StageRecursionData +public import LeanPool.KLRandomness.StageStep +public import LeanPool.KLRandomness.StageSyndrome +public import LeanPool.KLRandomness.StageSyndromeComputable +public import LeanPool.KLRandomness.StageSyndromeObjective +public import LeanPool.KLRandomness.StageWeights +public import LeanPool.KLRandomness.StoppingTranscript +public import LeanPool.KLRandomness.StrategyCountability +public import LeanPool.KLRandomness.UniformSupport +public import LeanPool.KLRandomness.UniformSupportCount diff --git a/LeanPool/KLRandomness/LateDropBound.lean b/LeanPool/KLRandomness/LateDropBound.lean new file mode 100644 index 0000000000..26842be35a --- /dev/null +++ b/LeanPool/KLRandomness/LateDropBound.lean @@ -0,0 +1,257 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.FutureNoDrop +public import LeanPool.KLRandomness.DropEvents + +/-! +# The Section 6 bound for late rank drops + +The hypotheses are estimates under the actual finite-stage laws. The infinite +law is the constructed `BlockProduct.law`. Horizon avoidance transfers the +partial-rank event, and the first-future-drop identity transfers the remaining +event. A measurable transcript partition then gives the late-drop bound. + +The separate constants below correspond to the paper's `4e_j`, `2e_j`, `e_j`, +and the sum of the later `e_k`. No candidate-pool or stage-existence premise is +hidden in this measure-theoretic implication. +-/ + +@[expose] public section + +namespace Klr.LateDropBound + +open MeasureTheory ProbabilityTheory StoppingTranscript +open scoped ENNReal + +/-- A block has some finite rank drop; equivalently its first-drop time is finite. -/ +def hasDrop (B : AffineBlock) (π : ScanRule) : Set Cantor := + (NoDrop.noDropEvent B π)ᶜ + +theorem measurableSet_hasDrop (B : AffineBlock) (π : ScanRule) : + MeasurableSet (hasDrop B π) := (NoDrop.measurableSet_noDropEvent B π).compl + +theorem hasDrop_eq_rankDropTailEvent (B : AffineBlock) (π : ScanRule) : + hasDrop B π = rankDropTailEvent B π 0 := by + rw [hasDrop, NoDrop.noDropEvent_eq_compl_rankDropTailEvent, compl_compl] + +theorem mem_hasDrop_of_rank_lt (B : AffineBlock) (π : ScanRule) (X : Cantor) + {m n : ℕ} (h : B.remainingRank π (π.transcript X m) < + B.remainingRank π (π.transcript X n)) : X ∈ hasDrop B π := by + intro hno + rw [(B.unreadFullRank_iff_remainingRank π _).mp (hno m), + (B.unreadFullRank_iff_remainingRank π _).mp (hno n)] at h + exact lt_irrefl _ h + +/-- A first drop is later than `N` whenever rank is still full at `N` and a drop occurs. -/ +theorem mem_rankDropTail_of_full_and_hasDrop (B : AffineBlock) (π : ScanRule) + (N : ℕ) (X : Cantor) (hfull : B.UnreadFullRank π (π.transcript X N)) + (hdrop : X ∈ hasDrop B π) : X ∈ rankDropTailEvent B π N := by + rw [hasDrop_eq_rankDropTailEvent] at hdrop + obtain ⟨n, _, hbefore, hfail⟩ := hdrop + refine ⟨n, ?_, hbefore, hfail⟩ + by_contra h + have hn : n + 1 ≤ N := by omega + exact hfail (NoDrop.survivalEvent_antitone B π hn hfull) + +/-- Partial unread row rank at a finite horizon. -/ +def partialEvent (B : AffineBlock) (π : ScanRule) (N : ℕ) : Set Cantor := + {X | 0 < B.remainingRank π (π.transcript X N) ∧ + B.remainingRank π (π.transcript X N) < B.rank} + +theorem measurableSet_partialEvent (B : AffineBlock) (π : ScanRule) (N : ℕ) : + MeasurableSet (partialEvent B π N) := + DropEvents.measurableSet_transcript_pred π N + (fun v => 0 < B.remainingRank π v ∧ B.remainingRank π v < B.rank) + +/-- The fixed-length transcripts satisfying an arbitrary horizon predicate. -/ +def horizonWords (N : ℕ) (P : List Bool → Prop) : Set (List Bool) := + {v | v.length = N ∧ P v} + +theorem horizonWords_prefixFree (N : ℕ) (P : List Bool → Prop) : + PrefixFree (horizonWords N P) := by + intro u v hu hv huv + exact huv.eq_of_length (hu.1.trans hv.1.symm) + +theorem horizonEvent_eq_union (π : ScanRule) (N : ℕ) (P : List Bool → Prop) : + {X : Cantor | P (π.transcript X N)} = unionEvent π (horizonWords N P) := by + ext X + constructor + · intro h + apply Set.mem_iUnion.mpr + refine ⟨⟨π.transcript X N, π.length_transcript X N, h⟩, ?_⟩ + change π.transcript X (π.transcript X N).length = π.transcript X N + rw [π.length_transcript] + · intro h + obtain ⟨v, hv⟩ := Set.mem_iUnion.mp h + change π.transcript X v.val.length = v.val at hv + rw [v.property.1] at hv + change P (π.transcript X N) + rw [hv] + exact v.property.2 + +/-- All horizon events have their actual finite-stage probabilities when the later +blocks retain full rank on every possible transcript through that horizon. -/ +theorem law_horizon_event (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) + (n : ℕ) (π : ScanRule) (N : ℕ) + (hfull : ∀ v, v.length = N → ∀ k, n ≤ k → (B k).UnreadFullRank π v) + (P : List Bool → Prop) : + BlockProduct.law B hdis {X | P (π.transcript X N)} = + PrefixStage.law B n {X | P (π.transcript X N)} := by + rw [horizonEvent_eq_union] + exact BlockProduct.law_unionEvent_eq_of_fullRank B hdis n π + (horizonWords_prefixFree N P) (fun v hv => hfull v hv.1) + +/-- Rank zero at the horizon rules out every later drop in that block. -/ +theorem not_mem_lateEvent_of_rank_zero (B : ℕ → AffineBlock) (π : ScanRule) + (V : ℕ → ℕ) (j : ℕ) (X : Cantor) + (hzero : (B j).remainingRank π (π.transcript X (V j)) = 0) : + X ∉ DropEvents.lateEvent B π V j := by + rintro ⟨t, ht, hdrop⟩ + have hd := (DropEvents.atTime_iff_rank_drop B π j X t).mp hdrop + have hm := (B j).remainingRank_transcript_antitone π X ht + dsimp only at hm + omega + +/-- A late drop is covered by partial rank at the horizon or by the first future-drop +event. The latter includes the currently imposed block and all subsequent blocks. -/ +theorem lateEvent_subset_partial_union_firstDropAfter (B : ℕ → AffineBlock) + (π : ScanRule) (V : ℕ → ℕ) (j : ℕ) + (havoid : ∀ v, v.length = V j → ∀ k, j < k → (B k).UnreadFullRank π v) : + DropEvents.lateEvent B π V j ⊆ + partialEvent (B j) π (V j) ∪ FutureNoDrop.firstDropAfter B j π (V j) := by + rintro X ⟨t, ht, hdrop⟩ + have hd := (DropEvents.atTime_iff_rank_drop B π j X t).mp hdrop + have hm := (B j).remainingRank_transcript_antitone π X ht + dsimp only at hm + have hpos : 0 < (B j).remainingRank π (π.transcript X (V j)) := by omega + by_cases hp : (B j).remainingRank π (π.transcript X (V j)) < (B j).rank + · exact Or.inl ⟨hpos, hp⟩ + · have heq : (B j).remainingRank π (π.transcript X (V j)) = (B j).rank := + le_antisymm ((B j).remainingRank_le π _) (Nat.le_of_not_gt hp) + have hsafe : FutureNoDrop.Safe B j π (π.transcript X (V j)) := by + intro k hk + rcases eq_or_lt_of_le hk with rfl | hjk + · exact ((B j).unreadFullRank_iff_remainingRank π _).mpr heq + · exact havoid _ (π.length_transcript X _) k hjk + apply Or.inr + apply (FutureNoDrop.mem_firstDropAfter_iff B j π (V j) X).mpr + exact ⟨hsafe, j, le_rfl, t + 1, by omega, by simpa using hd⟩ + +/-- The first-future-drop event splits according to whether the current block ever drops +and, on its no-drop part, according to the Borel transcript partition `H, Hᶜ`. -/ +theorem firstDropAfter_subset (B : ℕ → AffineBlock) (j : ℕ) (π : ScanRule) + (N : ℕ) (H : Set Cantor) : + FutureNoDrop.firstDropAfter B j π N ⊆ + (rankDropTailEvent (B j) π N ∪ + (π.observationMap ⁻¹' H ∩ NoDrop.noDropEvent (B j) π)) ∪ + ⋃ k : {k : ℕ // j < k}, π.observationMap ⁻¹' Hᶜ ∩ hasDrop (B k.val) π := by + classical + intro X hX + obtain ⟨hN, k, hk, t, ht, hdrop⟩ := + (FutureNoDrop.mem_firstDropAfter_iff B j π N X).mp hX + by_cases hno : X ∈ NoDrop.noDropEvent (B j) π + · by_cases hH : π.observationMap X ∈ H + · exact Or.inl (Or.inr ⟨hH, hno⟩) + · have hkd : X ∈ hasDrop (B k) π := mem_hasDrop_of_rank_lt (B k) π X hdrop + have hkj : k ≠ j := by + intro he + subst k + exact hkd hno + apply Or.inr + exact Set.mem_iUnion.mpr ⟨⟨k, by omega⟩, hH, hkd⟩ + · exact Or.inl (Or.inl (mem_rankDropTail_of_full_and_hasDrop (B j) π N X + (hN j le_rfl) hno)) + +/-- Adding the current block preserves the `H` part of its no-drop transcript law. -/ +theorem stage_H_noDrop (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) + (j : ℕ) (π : ScanRule) {H : Set Cantor} (hH : MeasurableSet H) : + PrefixStage.law B (j + 1) (π.observationMap ⁻¹' H ∩ NoDrop.noDropEvent (B j) π) = + PrefixStage.law B j (π.observationMap ⁻¹' H ∩ NoDrop.noDropEvent (B j) π) := by + rw [PrefixStage.law_succ] + exact NoDrop.nextStage_noDrop_borel (PrefixStage.prefixFamily B j) (B j) + (PrefixStage.prefixFamily_pairwise B hdis j) + (fun k => hdis (ne_of_lt k.isLt)) π hH + +/-- The stage estimate for the first future drop, before adding the partial-rank term. -/ +theorem stage_firstDropAfter_le (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) + (j : ℕ) (π : ScanRule) (N : ℕ) (H : Set Cantor) (hH : MeasurableSet H) + (β γ : ℝ≥0∞) (e : ℕ → ℝ≥0∞) + (htail : PrefixStage.law B (j + 1) (rankDropTailEvent (B j) π N) ≤ β) + (hhigh : PrefixStage.law B j + (π.observationMap ⁻¹' H ∩ NoDrop.noDropEvent (B j) π) ≤ γ) + (hlater : ∀ k, j < k → PrefixStage.law B (j + 1) + (π.observationMap ⁻¹' Hᶜ ∩ hasDrop (B k) π) ≤ e k) : + PrefixStage.law B (j + 1) (FutureNoDrop.firstDropAfter B j π N) ≤ + β + γ + ∑' k : {k : ℕ // j < k}, e k.val := by + have hhigh' : PrefixStage.law B (j + 1) + (π.observationMap ⁻¹' H ∩ NoDrop.noDropEvent (B j) π) ≤ γ := by + rw [stage_H_noDrop B hdis j π hH] + exact hhigh + calc + _ ≤ PrefixStage.law B (j + 1) + ((rankDropTailEvent (B j) π N ∪ + (π.observationMap ⁻¹' H ∩ NoDrop.noDropEvent (B j) π)) ∪ + ⋃ k : {k : ℕ // j < k}, π.observationMap ⁻¹' Hᶜ ∩ hasDrop (B k.val) π) := + measure_mono (firstDropAfter_subset B j π N H) + _ ≤ PrefixStage.law B (j + 1) + (rankDropTailEvent (B j) π N ∪ + (π.observationMap ⁻¹' H ∩ NoDrop.noDropEvent (B j) π)) + + PrefixStage.law B (j + 1) + (⋃ k : {k : ℕ // j < k}, π.observationMap ⁻¹' Hᶜ ∩ hasDrop (B k.val) π) := + measure_union_le _ _ + _ ≤ (PrefixStage.law B (j + 1) (rankDropTailEvent (B j) π N) + + PrefixStage.law B (j + 1) + (π.observationMap ⁻¹' H ∩ NoDrop.noDropEvent (B j) π)) + + ∑' k : {k : ℕ // j < k}, PrefixStage.law B (j + 1) + (π.observationMap ⁻¹' Hᶜ ∩ hasDrop (B k.val) π) := + add_le_add (measure_union_le _ _) (measure_iUnion_le _) + _ ≤ _ := add_le_add (add_le_add htail hhigh') + (tsum_le_tsum (fun k => hlater k.val k.property)) + +/-- The Section 6 late-drop estimate from genuine finite-stage hypotheses. +With `α = 4e_j`, `β = 2e_j`, and `γ = e_j`, the right side is `7e_j + ∑_{k>j} e_k`. -/ +theorem law_lateEvent_le (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) + (π : ScanRule) (V : ℕ → ℕ) (j : ℕ) (H : Set Cantor) (hH : MeasurableSet H) + (α β γ : ℝ≥0∞) (e : ℕ → ℝ≥0∞) + (havoid : ∀ v, v.length = V j → ∀ k, j < k → (B k).UnreadFullRank π v) + (hpartial : PrefixStage.law B (j + 1) (partialEvent (B j) π (V j)) ≤ α) + (htail : PrefixStage.law B (j + 1) (rankDropTailEvent (B j) π (V j)) ≤ β) + (hhigh : PrefixStage.law B j + (π.observationMap ⁻¹' H ∩ NoDrop.noDropEvent (B j) π) ≤ γ) + (hlater : ∀ k, j < k → PrefixStage.law B (j + 1) + (π.observationMap ⁻¹' Hᶜ ∩ hasDrop (B k) π) ≤ e k) : + BlockProduct.law B hdis (DropEvents.lateEvent B π V j) ≤ + α + β + γ + ∑' k : {k : ℕ // j < k}, e k.val := by + have hp : BlockProduct.law B hdis (partialEvent (B j) π (V j)) = + PrefixStage.law B (j + 1) (partialEvent (B j) π (V j)) := by + exact law_horizon_event B hdis (j + 1) π (V j) + (fun v hv k hk => havoid v hv k (by omega)) + (fun v => 0 < (B j).remainingRank π v ∧ (B j).remainingRank π v < (B j).rank) + calc + _ ≤ BlockProduct.law B hdis + (partialEvent (B j) π (V j) ∪ FutureNoDrop.firstDropAfter B j π (V j)) := + measure_mono (lateEvent_subset_partial_union_firstDropAfter B π V j havoid) + _ ≤ BlockProduct.law B hdis (partialEvent (B j) π (V j)) + + BlockProduct.law B hdis (FutureNoDrop.firstDropAfter B j π (V j)) := + measure_union_le _ _ + _ = PrefixStage.law B (j + 1) (partialEvent (B j) π (V j)) + + PrefixStage.law B (j + 1) (FutureNoDrop.firstDropAfter B j π (V j)) := by + rw [hp, FutureNoDrop.law_firstDropAfter_of_le B hdis j (j + 1) (Nat.le_succ j)] + _ ≤ α + (β + γ + ∑' k : {k : ℕ // j < k}, e k.val) := + add_le_add hpartial (stage_firstDropAfter_le B hdis j π (V j) H hH β γ e + htail hhigh hlater) + _ = _ := by ac_rfl + +end Klr.LateDropBound diff --git a/LeanPool/KLRandomness/MLImpliesKL.lean b/LeanPool/KLRandomness/MLImpliesKL.lean new file mode 100644 index 0000000000..98a63ad1cf --- /dev/null +++ b/LeanPool/KLRandomness/MLImpliesKL.lean @@ -0,0 +1,105 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.EffectiveScan +public import LeanPool.KLRandomness.MaximalInequality +public import LeanPool.KLRandomness.ComputableRational +import Mathlib.Tactic.Linarith + +/-! +# Martin-Löf randomness implies Kolmogorov–Loveland randomness + +A fixed-precision rational approximation to capital suffices to construct the +test: enumerate transcripts where the approximation exceeds `2^m + 1`. The +error is at most one, so the maximal inequality gives the level bound; capital +above `2^m + 2` ensures membership. Uniform higher precision is not needed in +this particular argument. +-/ + +@[expose] public section + +namespace Klr + +open MeasureTheory RationalComputability +open scoped ENNReal + +private theorem computable_two_pow_rat : Computable (fun n : ℕ => (2 : ℚ) ^ n) := by + have hproj : Computable (fun p : ℕ × (ℕ × ℚ) => p.2.2) := + Computable.snd.comp Computable.snd + have hs₀ := primrec_rat_mul.to_comp.comp hproj (Computable.const 2) + have hs : Computable₂ (fun (_ : ℕ) (p : ℕ × ℚ) => p.2 * 2) := + hs₀.to₂.of_eq (fun _ => rfl) + apply (Computable.nat_rec Computable.id (Computable.const 1) hs).of_eq + intro n + induction n with + | zero => rfl + | succ n ih => simpa only [id_eq, Nat.rec_add_one, pow_succ] using congrArg (· * 2) ih + +/-- Every total computable-real betting strategy has one genuine Martin-Löf test covering +all inputs on which it succeeds. -/ +theorem BettingStrategy.exists_test_covers_success (s : BettingStrategy) : + ∃ T : MartinLofTest, ∀ X, s.Succeeds X → T.Fails X := by + obtain ⟨q, hq, herror⟩ := s.computable_capital + have hc₀ := (computable_rat_of_numDen hq).comp (Computable.id.pair (Computable.const 0)) + have hc : Computable (fun v : List Bool => q v 0) := hc₀.of_eq (fun _ => rfl) + let R : ℕ × List Bool → Prop := fun p => (2 : ℚ) ^ p.1 + 1 < q p.2 0 + have hR : ComputablePred R := by + have hq₀ := hc.comp (Computable.snd : Computable (fun p : ℕ × List Bool => p.2)) + have hp₀ := computable_two_pow_rat.comp + (Computable.fst : Computable (fun p : ℕ × List Bool => p.1)) + have ht₀ := primrec_rat_add.to_comp.comp hp₀ (Computable.const 1) + have hbool₀ := primrec_rat_le.computablePred.decide.comp (hq₀.pair ht₀) + have hbool : Computable (fun p : ℕ × List Bool => + decide (q p.2 0 ≤ (2 : ℚ) ^ p.1 + 1)) := hbool₀.of_eq (fun _ => rfl) + have hle : ComputablePred (fun p : ℕ × List Bool => q p.2 0 ≤ (2 : ℚ) ^ p.1 + 1) := + hbool.computablePred + exact hle.not.of_eq (fun _ => not_le) + let U := EffectiveScan.openEvent s.scan R + have hU : IsUniformlyEffectivelyOpen U := EffectiveScan.openEvent_uniform s.scan hR + have hbound : ∀ m, fairCoin (U m) ≤ (1 / 2 : ℝ≥0∞) ^ m := by + intro m + apply (measure_mono (show U m ⊆ s.capital.exceeds s.scan ((2 : ℝ) ^ m) from ?_)).trans + (s.capital.measure_exceeds_pow_le s.scan m) + rintro X ⟨v, hv, hX⟩ + have he := herror v 0 + simp only [pow_zero] at he + have hqv : (2 : ℝ) ^ m + 1 < (q v 0 : ℝ) := by + have hcast := (Rat.cast_lt (K := ℝ)).mpr (show (2 : ℚ) ^ m + 1 < q v 0 from hv) + simpa only [Rat.cast_add, Rat.cast_pow, Rat.cast_ofNat, Rat.cast_one] using hcast + have hd : (2 : ℝ) ^ m < s.capital.value v := by + have he' := (abs_le.mp he).2 + linarith + exact ⟨v.length, by simpa only [hX] using hd⟩ + obtain ⟨T, hT⟩ := MartinLofTest.exists_of_uniform hU hbound + refine ⟨T, fun X hsuccess m => ?_⟩ + change X ∈ programOpen T.code m + rw [hT m] + obtain ⟨n, hn⟩ := hsuccess ((2 : ℝ) ^ m + 2) + let v := s.scan.transcript X n + have he := herror v 0 + simp only [pow_zero] at he + have hqv : (2 : ℝ) ^ m + 1 < (q v 0 : ℝ) := by + have he' := (abs_le.mp he).1 + change (2 : ℝ) ^ m + 2 < s.capital.value v at hn + linarith + refine ⟨v, ?_, ?_⟩ + · change (2 : ℚ) ^ m + 1 < q v 0 + apply (Rat.cast_lt (K := ℝ)).mp + simpa only [Rat.cast_add, Rat.cast_pow, Rat.cast_ofNat, Rat.cast_one] using hqv + · simp [v] + +/-- The standard containment, for the repository's actual effective-test and strategy types. -/ +theorem MartinLofRandom.kolmogorovLovelandRandom {X : Cantor} (hX : MartinLofRandom X) : + KolmogorovLovelandRandom X := by + intro s hs + obtain ⟨T, hT⟩ := s.exists_test_covers_success + exact hX T (hT X hs) + +end Klr diff --git a/LeanPool/KLRandomness/MartinLof.lean b/LeanPool/KLRandomness/MartinLof.lean new file mode 100644 index 0000000000..df82ca1f09 --- /dev/null +++ b/LeanPool/KLRandomness/MartinLof.lean @@ -0,0 +1,121 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.EffectiveOpen +public import Mathlib.Analysis.SpecificLimits.Basic +import Mathlib.Tactic.NormNum + +/-! +# Martin-Löf tests and randomness + +Test levels are numbered from zero. The bound is `(1/2)^n`; shifting the paper's +positive numbering by one gives the same randomness notion. Every test carries +one actual partial-recursive code, enforcing uniform effectiveness across levels. +-/ + +@[expose] public section + +namespace Klr + +open MeasureTheory +open scoped ENNReal + +/-- A Martin-Löf test is one program enumerating all its levels, with the usual bounds. -/ +structure MartinLofTest where + /-- A single partial-recursive program recognizing the cylinders for all test levels. -/ + code : Nat.Partrec.Code + measure_le : ∀ n, fairCoin (programOpen code n) ≤ (1 / 2 : ℝ≥0∞) ^ n + +namespace MartinLofTest + +/-- Every uniformly effectively open family satisfying the bounds is represented by a test. -/ +theorem exists_of_uniform {U : ℕ → Set Cantor} (hU : IsUniformlyEffectivelyOpen U) + (hbound : ∀ n, fairCoin (U n) ≤ (1 / 2 : ℝ≥0∞) ^ n) : + ∃ T : MartinLofTest, ∀ n, programOpen T.code n = U n := by + obtain ⟨c, hc⟩ := (isUniformlyEffectivelyOpen_iff_exists_program U).mp hU + exact ⟨⟨c, fun n => by rw [← hc n]; exact hbound n⟩, fun n => (hc n).symm⟩ + +/-- The `n`th open level of a test. -/ +def level (T : MartinLofTest) (n : ℕ) : Set Cantor := programOpen T.code n + +theorem uniform (T : MartinLofTest) : IsUniformlyEffectivelyOpen T.level := + programOpen_uniform T.code + +theorem measurableSet_level (T : MartinLofTest) (n : ℕ) : MeasurableSet (T.level n) := + (T.uniform.level n).measurableSet + +/-- A sequence fails a test when it belongs to all of its levels. -/ +def Fails (T : MartinLofTest) (X : Cantor) : Prop := ∀ n, X ∈ T.level n + +theorem measure_failure (T : MartinLofTest) : fairCoin {X | T.Fails X} = 0 := by + apply ENNReal.eq_zero_of_le_mul_pow (ε := 1) (r := (1 / 2 : ℝ≥0∞)) (by norm_num) + intro n + simpa using (measure_mono (show {X | T.Fails X} ⊆ T.level n from fun _ h => h n)).trans + (T.measure_le n) + +theorem ae_not_fails (T : MartinLofTest) : ∀ᵐ X ∂fairCoin, ¬T.Fails X := by + simpa only [ae_iff, not_not] using T.measure_failure + +instance : Countable MartinLofTest := + Function.Injective.countable (f := MartinLofTest.code) (by + intro T S h + cases T + cases S + cases h + rfl) + +end MartinLofTest + +/-- Martin-Löf randomness for the fair-coin measure. -/ +def MartinLofRandom (X : Cantor) : Prop := ∀ T : MartinLofTest, ¬T.Fails X + +theorem not_martinLofRandom_iff (X : Cantor) : + ¬MartinLofRandom X ↔ ∃ T : MartinLofTest, T.Fails X := by + simp [MartinLofRandom] + +theorem not_martinLofRandom_of_mem (T : MartinLofTest) {X : Cantor} + (hX : ∀ n, X ∈ T.level n) : ¬MartinLofRandom X := + fun h => h T hX + +/-- The usual set-based formulation can be used without manipulating program codes. -/ +theorem not_martinLofRandom_of_uniform {U : ℕ → Set Cantor} + (hU : IsUniformlyEffectivelyOpen U) + (hbound : ∀ n, fairCoin (U n) ≤ (1 / 2 : ℝ≥0∞) ^ n) + {X : Cantor} (hX : ∀ n, X ∈ U n) : ¬MartinLofRandom X := by + obtain ⟨T, hT⟩ := MartinLofTest.exists_of_uniform hU hbound + apply not_martinLofRandom_of_mem T + intro n + change X ∈ programOpen T.code n + rw [hT n] + exact hX n + +/-- Equivalence with the standard definition using uniformly effectively open sets. -/ +theorem martinLofRandom_iff (X : Cantor) : + MartinLofRandom X ↔ + ∀ U : ℕ → Set Cantor, IsUniformlyEffectivelyOpen U → + (∀ n, fairCoin (U n) ≤ (1 / 2 : ℝ≥0∞) ^ n) → ∃ n, X ∉ U n := by + classical + constructor + · intro h U hU hb + by_contra hfail + have hX : ∀ n, X ∈ U n := by simpa using hfail + exact not_martinLofRandom_of_uniform hU hb hX h + · intro h T hf + obtain ⟨n, hn⟩ := h T.level T.uniform T.measure_le + exact hn (hf n) + +/-- Every individual effective test has a null failure set, and there are countably many codes. -/ +theorem ae_martinLofRandom : ∀ᵐ X ∂fairCoin, MartinLofRandom X := + ae_all_iff.mpr fun T => T.ae_not_fails + +theorem exists_martinLofRandom : ∃ X : Cantor, MartinLofRandom X := + ae_martinLofRandom.exists + +end Klr diff --git a/LeanPool/KLRandomness/MaximalInequality.lean b/LeanPool/KLRandomness/MaximalInequality.lean new file mode 100644 index 0000000000..6cc425adc4 --- /dev/null +++ b/LeanPool/KLRandomness/MaximalInequality.lean @@ -0,0 +1,173 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.ScanMeasure +public import Mathlib.MeasureTheory.Measure.Continuity +import Mathlib.Tactic.GCongr +import Mathlib.Tactic.NormNum + +/-! +# The maximal inequality for adaptive fair capital + +Finite hitting events are expanded down the transcript tree. Fairness preserves +the capital-weighted cylinder mass at each split. This gives the probability +bound for ever exceeding `2^m`, without introducing a separate filtration. +-/ + +@[expose] public section + +namespace Klr.CapitalProcess + +open MeasureTheory +open scoped ENNReal + +/-- Inputs on which the capital ever strictly exceeds a threshold. -/ +def exceeds (d : CapitalProcess) (π : ScanRule) (a : ℝ) : Set Cantor := + {X | ∃ n, a < d.value (π.transcript X n)} + +/-- The finite transcript subtree obtained by stopping as soon as capital exceeds `a`. -/ +noncomputable def finiteHit (d : CapitalProcess) (π : ScanRule) (a : ℝ) : + List Bool → ℕ → Set Cantor + | v, 0 => if a < d.value v then {X | π.transcript X v.length = v} else ∅ + | v, n + 1 => if a < d.value v then {X | π.transcript X v.length = v} + else d.finiteHit π a (v ++ [false]) n ∪ d.finiteHit π a (v ++ [true]) n + +theorem weighted_children (d : CapitalProcess) (v : List Bool) : + ENNReal.ofReal (d.value (v ++ [false])) * (1 / 2 : ℝ≥0∞) ^ (v ++ [false]).length + + ENNReal.ofReal (d.value (v ++ [true])) * (1 / 2 : ℝ≥0∞) ^ (v ++ [true]).length = + ENNReal.ofReal (d.value v) * (1 / 2 : ℝ≥0∞) ^ v.length := by + simp only [List.length_append, List.length_singleton] + rw [← add_mul, ← ENNReal.ofReal_add (d.nonneg _) (d.nonneg _), d.fair, + ENNReal.ofReal_mul (by norm_num : (0 : ℝ) ≤ 2), pow_succ] + norm_num only [ENNReal.ofReal_ofNat] + calc + 2 * ENNReal.ofReal (d.value v) * ((1 / 2 : ℝ≥0∞) ^ v.length * (1 / 2)) = + ENNReal.ofReal (d.value v) * (1 / 2 : ℝ≥0∞) ^ v.length * (2 * (1 / 2)) := by + ac_rfl + _ = _ := by + rw [one_div, ENNReal.mul_inv_cancel (by norm_num) (by norm_num), mul_one] + +/-- The weighted maximal inequality on every finite transcript subtree. -/ +theorem finiteHit_bound (d : CapitalProcess) (π : ScanRule) (a : ℝ) + (v : List Bool) (n : ℕ) : + ENNReal.ofReal a * fairCoin (d.finiteHit π a v n) ≤ + ENNReal.ofReal (d.value v) * (1 / 2 : ℝ≥0∞) ^ v.length := by + induction n generalizing v with + | zero => + by_cases h : a < d.value v + · simp only [finiteHit, ite_eq_left h, π.fairCoin_transcript] + gcongr + · simp [finiteHit, h] + | succ n ih => + by_cases h : a < d.value v + · simp only [finiteHit, ite_eq_left h, π.fairCoin_transcript] + gcongr + · rw [finiteHit, ite_eq_right h] + calc + _ ≤ ENNReal.ofReal a * (fairCoin (d.finiteHit π a (v ++ [false]) n) + + fairCoin (d.finiteHit π a (v ++ [true]) n)) := + by + gcongr + exact measure_union_le _ _ + _ = _ := mul_add _ _ _ + _ ≤ _ := add_le_add (ih (v ++ [false])) (ih (v ++ [true])) + _ = _ := d.weighted_children v + +theorem finiteHit_subset_exceeds (d : CapitalProcess) (π : ScanRule) (a : ℝ) + (v : List Bool) (n : ℕ) : d.finiteHit π a v n ⊆ d.exceeds π a := by + induction n generalizing v with + | zero => + by_cases h : a < d.value v + · intro X hX + have hv : π.transcript X v.length = v := by simpa [finiteHit, h] using hX + exact ⟨v.length, by simpa [hv] using h⟩ + · simp [finiteHit, h] + | succ n ih => + by_cases h : a < d.value v + · intro X hX + have hv : π.transcript X v.length = v := by simpa [finiteHit, h] using hX + exact ⟨v.length, by simpa [hv] using h⟩ + · simpa only [finiteHit, ite_eq_right h] using Set.union_subset (ih _) (ih _) + +theorem mem_finiteHit_of_prefix (d : CapitalProcess) (π : ScanRule) (a : ℝ) + (X : Cantor) (v : List Bool) (n : ℕ) (hv : π.transcript X v.length = v) + (h : ∃ k ≤ n, a < d.value (π.transcript X (v.length + k))) : + X ∈ d.finiteHit π a v n := by + induction n generalizing v with + | zero => + obtain ⟨k, hk, h⟩ := h + have : k = 0 := by omega + subst k + have ha : a < d.value v := by simpa [hv] using h + simpa [finiteHit, ha] using hv + | succ n ih => + by_cases ha : a < d.value v + · simpa [finiteHit, ha] using hv + · obtain ⟨k, hk, h⟩ := h + have hk0 : k ≠ 0 := by + intro heq + subst k + exact ha (by simpa [hv] using h) + obtain ⟨j, rfl⟩ := Nat.exists_eq_succ_of_ne_zero hk0 + let b := X (π.query v) + have hvb : π.transcript X (v ++ [b]).length = v ++ [b] := by + simp [ScanRule.transcript_succ, hv, b] + have hb : X ∈ d.finiteHit π a (v ++ [b]) n := by + apply ih (v ++ [b]) hvb + refine ⟨j, by omega, ?_⟩ + simpa [Nat.add_assoc, Nat.add_comm 1 j] using h + rw [finiteHit, ite_eq_right ha] + cases hbval : b + · exact Or.inl (by simpa [hbval] using hb) + · exact Or.inr (by simpa [hbval] using hb) + +theorem finiteHit_mono (d : CapitalProcess) (π : ScanRule) (a : ℝ) (v : List Bool) : + Monotone (d.finiteHit π a v) := by + apply monotone_nat_of_le_succ + intro n + induction n generalizing v with + | zero => + by_cases h : a < d.value v <;> simp [finiteHit, h] + | succ n ih => + by_cases h : a < d.value v + · simp [finiteHit, h] + · simp only [finiteHit, ite_eq_right h] + exact Set.union_subset_union (ih _) (ih _) + +theorem exceeds_eq_iUnion_finiteHit (d : CapitalProcess) (π : ScanRule) (a : ℝ) : + d.exceeds π a = ⋃ n, d.finiteHit π a [] n := by + ext X + constructor + · rintro ⟨n, hn⟩ + exact Set.mem_iUnion.mpr ⟨n, d.mem_finiteHit_of_prefix π a X [] n (by simp) + ⟨n, le_rfl, by simpa using hn⟩⟩ + · intro h + obtain ⟨n, hn⟩ := Set.mem_iUnion.mp h + exact d.finiteHit_subset_exceeds π a [] n hn + +/-- Every adaptive fair strategy exceeds `2^m` on a set of measure at most `2^-m`. -/ +theorem measure_exceeds_pow_le (d : CapitalProcess) (π : ScanRule) (m : ℕ) : + fairCoin (d.exceeds π ((2 : ℝ) ^ m)) ≤ (1 / 2 : ℝ≥0∞) ^ m := by + rw [d.exceeds_eq_iUnion_finiteHit, (d.finiteHit_mono π ((2 : ℝ) ^ m) []).measure_iUnion] + apply iSup_le + intro n + have h := d.finiteHit_bound π ((2 : ℝ) ^ m) [] n + simp only [d.initial, ENNReal.ofReal_one, List.length_nil, pow_zero, mul_one, + ENNReal.ofReal_pow (by norm_num : (0 : ℝ) ≤ 2), ENNReal.ofReal_ofNat] at h + have hc : (1 / 2 : ℝ≥0∞) ^ m * (2 : ℝ≥0∞) ^ m = 1 := by + rw [← mul_pow, one_div, ENNReal.inv_mul_cancel (by norm_num) (by norm_num), one_pow] + calc + _ = (1 / 2 : ℝ≥0∞) ^ m * + ((2 : ℝ≥0∞) ^ m * fairCoin (d.finiteHit π ((2 : ℝ) ^ m) [] n)) := by + rw [← mul_assoc, hc, one_mul] + _ ≤ (1 / 2 : ℝ≥0∞) ^ m * 1 := by gcongr + _ = _ := mul_one _ + +end Klr.CapitalProcess diff --git a/LeanPool/KLRandomness/NoDrop.lean b/LeanPool/KLRandomness/NoDrop.lean new file mode 100644 index 0000000000..533364804b --- /dev/null +++ b/LeanPool/KLRandomness/NoDrop.lean @@ -0,0 +1,445 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.RemainingRank +public import Mathlib.MeasureTheory.Measure.Continuity + +/-! +# Transcript laws restricted to no rank drop + +The finite-stage cylinder identity extends to every Borel transcript event on +the event that the new block never loses full unread rank. The proof first +intersects cylinders with finite-horizon survival events, passes to the +decreasing intersection, and then uses uniqueness of finite measures on the +prefix-cylinder generator of Cantor space. +-/ + +@[expose] public section + +namespace Klr + +open MeasureTheory ProbabilityTheory +open scoped ENNReal + +namespace StoppingTranscript + +/-- Extending a transcript only shrinks its input event. -/ +theorem inputEvent_subset_of_prefix (π : ScanRule) {u v : List Bool} (h : u <+: v) : + inputEvent π v ⊆ inputEvent π u := by + intro X hX + change π.transcript X v.length = v at hX + change π.transcript X u.length = u + rw [← π.transcript_take X h.length_le, hX] + exact (List.prefix_iff_eq_take.mp h).symm + +end StoppingTranscript + +/-- Ordinary prefix cylinders are the input events of the monotone scan. -/ +theorem cylinder_eq_monotone_inputEvent (v : List Bool) : + cylinder v = StoppingTranscript.inputEvent ScanRule.monotone v := by + ext X + change (∀ i < v.length, X i = v.getD i false) ↔ _ + rw [StoppingTranscript.inputEvent, Set.mem_ofPred, ScanRule.transcript_eq_iff] + constructor <;> intro h i hi <;> + simpa [ScanRule.monotone, List.length_take, Nat.min_eq_left hi.le] using h i hi + +theorem cylinder_subset_of_prefix {u v : List Bool} (h : u <+: v) : + cylinder v ⊆ cylinder u := by + rw [cylinder_eq_monotone_inputEvent, cylinder_eq_monotone_inputEvent] + exact StoppingTranscript.inputEvent_subset_of_prefix ScanRule.monotone h + +/-- A one-coordinate specification is a countable union of ordinary prefix cylinders. -/ +theorem coordinate_event_eq_iUnion_cylinders (n : ℕ) (b : Bool) : + {X : Cantor | X n = b} = + ⋃ v : {v : List Bool // v.length = n + 1 ∧ v.getD n false = b}, cylinder v.val := by + ext X + constructor + · intro hb + let v := ScanRule.monotone.transcript X (n + 1) + have hv : v.length = n + 1 ∧ v.getD n false = b := by + constructor + · simp only [v, ScanRule.length_transcript] + · rw [ScanRule.getD_transcript ScanRule.monotone X (by omega)] + change X (ScanRule.monotone.transcript X n).length = b + rwa [ScanRule.length_transcript] + apply Set.mem_iUnion.mpr + refine ⟨⟨v, hv⟩, ?_⟩ + rw [cylinder_eq_monotone_inputEvent] + change ScanRule.monotone.transcript X v.length = v + rw [hv.1] + · intro h + obtain ⟨v, hv⟩ := Set.mem_iUnion.mp h + exact (hv n (by rw [v.property.1]; omega)).trans v.property.2 + +/-- Prefix cylinders form a π-system. -/ +theorem isPiSystem_cylinders : IsPiSystem (Set.range cylinder) := by + rintro _ ⟨u, rfl⟩ _ ⟨v, rfl⟩ ⟨X, hu, hv⟩ + rw [cylinder_eq_monotone_inputEvent] at hu hv + rcases StoppingTranscript.comparable_of_mem_inputEvent ScanRule.monotone hu hv with h | h + · exact ⟨v, (Set.inter_eq_right.mpr (cylinder_subset_of_prefix h)).symm⟩ + · exact ⟨u, (Set.inter_eq_left.mpr (cylinder_subset_of_prefix h)).symm⟩ + +/-- The product measurable space on Cantor space is generated by prefix cylinders. -/ +theorem measurableSpace_eq_generateFrom_cylinders : + (inferInstance : MeasurableSpace Cantor) = + MeasurableSpace.generateFrom (Set.range cylinder) := by + apply le_antisymm + · have h : @Measurable Cantor Cantor + (MeasurableSpace.generateFrom (Set.range cylinder)) inferInstance id := by + let : MeasurableSpace Cantor := MeasurableSpace.generateFrom (Set.range cylinder) + apply measurable_pi_iff.mpr + intro n + apply measurable_to_countable' + intro b + change @MeasurableSet Cantor (MeasurableSpace.generateFrom (Set.range cylinder)) + {X | X n = b} + rw [coordinate_event_eq_iUnion_cylinders] + exact MeasurableSet.iUnion fun v => + MeasurableSpace.measurableSet_generateFrom (Set.mem_range_self v.val) + exact h + · exact MeasurableSpace.generateFrom_le (fun _ ⟨v, hv⟩ => hv ▸ measurableSet_cylinder v) + +/-- A finite measure on Cantor space is determined by the probabilities of finite prefixes. -/ +theorem measure_eq_of_cylinders (μ ν : Measure Cantor) [IsFiniteMeasure μ] + (h : ∀ v, μ (cylinder v) = ν (cylinder v)) : μ = ν := by + apply ext_of_generate_finite (Set.range cylinder) measurableSpace_eq_generateFrom_cylinders + isPiSystem_cylinders + · rintro _ ⟨v, rfl⟩ + exact h v + · simpa using h [] + +/-- An arbitrary condition on a fixed finite prefix gives a measurable cylinder union. -/ +theorem prefix_event_eq_iUnion_cylinders (P : List Bool → Prop) (n : ℕ) : + {X : Cantor | P (ScanRule.inputPrefix X n)} = + ⋃ v : {v : List Bool // v.length = n ∧ P v}, cylinder v.val := by + ext X + constructor + · intro h + change P (ScanRule.inputPrefix X n) at h + let v := ScanRule.monotone.transcript X n + have hv : v.length = n ∧ P v := + ⟨ScanRule.length_transcript _ _ _, by simpa only [v, ScanRule.monotone_transcript] using h⟩ + apply Set.mem_iUnion.mpr + refine ⟨⟨v, hv⟩, ?_⟩ + rw [cylinder_eq_monotone_inputEvent] + change ScanRule.monotone.transcript X v.length = v + rw [hv.1] + · intro h + obtain ⟨v, hv⟩ := Set.mem_iUnion.mp h + rw [cylinder_eq_monotone_inputEvent] at hv + change ScanRule.monotone.transcript X v.val.length = v.val at hv + rw [v.property.1, ScanRule.monotone_transcript] at hv + change P (ScanRule.inputPrefix X n) + rw [hv] + exact v.property.2 + +theorem measurableSet_prefix_event (P : List Bool → Prop) (n : ℕ) : + MeasurableSet {X : Cantor | P (ScanRule.inputPrefix X n)} := by + rw [prefix_event_eq_iUnion_cylinders] + exact MeasurableSet.iUnion fun v => measurableSet_cylinder v.val + +namespace ScanRule + +/-- The entire sequence of answers observed by a total adaptive scan. -/ +def observationMap (π : ScanRule) (X : Cantor) : Cantor := + fun n => X (π.query (π.transcript X n)) + +/-- The infinite observation map has the prescribed finite transcript as every prefix. -/ +theorem observationMap_mem_cylinder_iff (π : ScanRule) (X : Cantor) (v : List Bool) : + π.observationMap X ∈ cylinder v ↔ π.transcript X v.length = v := by + constructor + · intro h + apply List.ext_getElem (π.length_transcript X v.length) + intro i hi hv + have he := π.getD_transcript X hv + rw [List.getD_eq_getElem _ _ hi] at he + rw [he] + exact (h i hv).trans (List.getD_eq_getElem _ _ hv) + · intro h i hi + change X (π.query (π.transcript X i)) = v.getD i false + rw [← π.getD_transcript X hi, h] + +theorem observationMap_preimage_cylinder (π : ScanRule) (v : List Bool) : + π.observationMap ⁻¹' cylinder v = StoppingTranscript.inputEvent π v := by + ext X + exact π.observationMap_mem_cylinder_iff X v + +theorem inputPrefix_observationMap (π : ScanRule) (X : Cantor) (n : ℕ) : + inputPrefix (π.observationMap X) n = π.transcript X n := by + have h : π.observationMap X ∈ cylinder (π.transcript X n) := by + apply (π.observationMap_mem_cylinder_iff X _).mpr + rw [π.length_transcript] + rw [cylinder_eq_monotone_inputEvent] at h + change ScanRule.monotone.transcript (π.observationMap X) (π.transcript X n).length = + π.transcript X n at h + simpa only [π.length_transcript, ScanRule.monotone_transcript] using h + +/-- Measurability follows from the finite transcript preimages of the cylinder generator. -/ +theorem measurable_observationMap (π : ScanRule) : Measurable π.observationMap := by + suffices h : @Measurable Cantor Cantor inferInstance + (MeasurableSpace.generateFrom (Set.range cylinder)) π.observationMap by + rwa [← measurableSpace_eq_generateFrom_cylinders] at h + apply measurable_generateFrom + rintro _ ⟨v, rfl⟩ + rw [observationMap_preimage_cylinder] + exact StoppingTranscript.measurableSet_inputEvent π v + +end ScanRule + +namespace NoDrop + +open StoppingTranscript + +/-- Full unread rank remains after the first `n` observations. -/ +def survivalEvent (B : AffineBlock) (π : ScanRule) (n : ℕ) : Set Cantor := + {X | B.UnreadFullRank π (π.transcript X n)} + +/-- The new block never loses full unread rank along the scan. -/ +def noDropEvent (B : AffineBlock) (π : ScanRule) : Set Cantor := + {X | ∀ n, B.UnreadFullRank π (π.transcript X n)} + +/-- The event `T = ∞`, viewed as a Borel set of infinite answer transcripts. -/ +def noDropTranscripts (B : AffineBlock) (π : ScanRule) : Set Cantor := + {Y | ∀ n, B.UnreadFullRank π (ScanRule.inputPrefix Y n)} + +theorem measurableSet_noDropTranscripts (B : AffineBlock) (π : ScanRule) : + MeasurableSet (noDropTranscripts B π) := by + change MeasurableSet {Y | ∀ n, B.UnreadFullRank π (ScanRule.inputPrefix Y n)} + simp only [Set.ofPred_forall] + exact MeasurableSet.iInter (fun n => measurableSet_prefix_event (B.UnreadFullRank π) n) + +theorem observationMap_preimage_noDropTranscripts (B : AffineBlock) (π : ScanRule) : + π.observationMap ⁻¹' noDropTranscripts B π = noDropEvent B π := by + ext X + simp only [Set.mem_preimage, noDropTranscripts, noDropEvent, Set.mem_ofPred_eq, + π.inputPrefix_observationMap] + +theorem survivalEvent_antitone (B : AffineBlock) (π : ScanRule) : + Antitone (survivalEvent B π) := by + intro m n h X hX + apply (B.unreadFullRank_iff_remainingRank π _).mpr + apply le_antisymm (B.remainingRank_le π _) + rw [← (B.unreadFullRank_iff_remainingRank π _).mp hX] + exact B.remainingRank_transcript_antitone π X h + +/-- Fixed-length extensions which retain full unread rank. -/ +def survivingExtensions (B : AffineBlock) (π : ScanRule) (v : List Bool) (n : ℕ) : + Set (List Bool) := + {w | w.length = n ∧ v <+: w ∧ B.UnreadFullRank π w} + +theorem survivingExtensions_prefixFree (B : AffineBlock) (π : ScanRule) + (v : List Bool) (n : ℕ) : PrefixFree (survivingExtensions B π v n) := by + intro u w hu hw h + exact h.eq_of_length (hu.1.trans hw.1.symm) + +/-- A transcript cylinder intersected with finite survival is a disjoint union of +full-rank extensions at that horizon. -/ +theorem inputEvent_inter_survival_eq_union (B : AffineBlock) (π : ScanRule) + (v : List Bool) (n : ℕ) (hn : v.length ≤ n) : + inputEvent π v ∩ survivalEvent B π n = + unionEvent π (survivingExtensions B π v n) := by + ext X + constructor + · rintro ⟨hv, hfull⟩ + change π.transcript X v.length = v at hv + have hw : π.transcript X n ∈ survivingExtensions B π v n := by + refine ⟨π.length_transcript X n, ?_, hfull⟩ + simpa only [hv] using π.transcript_prefix X hn + apply Set.mem_iUnion.mpr + refine ⟨⟨π.transcript X n, hw⟩, ?_⟩ + change π.transcript X (π.transcript X n).length = π.transcript X n + rw [π.length_transcript] + · intro h + obtain ⟨w, hw⟩ := Set.mem_iUnion.mp h + refine ⟨inputEvent_subset_of_prefix π w.property.2.1 hw, ?_⟩ + change π.transcript X w.val.length = w.val at hw + rw [w.property.1] at hw + change B.UnreadFullRank π (π.transcript X n) + rw [hw] + exact w.property.2.2 + +theorem measurableSet_survivalEvent (B : AffineBlock) (π : ScanRule) (n : ℕ) : + MeasurableSet (survivalEvent B π n) := by + have h := inputEvent_inter_survival_eq_union B π [] n (by simp) + have he : inputEvent π [] = Set.univ := by + ext X + simp [inputEvent] + rw [he, Set.univ_inter] at h + rw [h] + exact measurableSet_unionEvent π _ + +theorem noDropEvent_eq_iInter (B : AffineBlock) (π : ScanRule) : + noDropEvent B π = ⋂ n, survivalEvent B π n := by + ext X + simp [noDropEvent, survivalEvent] + +theorem measurableSet_noDropEvent (B : AffineBlock) (π : ScanRule) : + MeasurableSet (noDropEvent B π) := by + rw [noDropEvent_eq_iInter] + exact MeasurableSet.iInter (measurableSet_survivalEvent B π) + +/-- No loss of full rank is exactly the absence of every finite strict rank decrease. -/ +theorem mem_noDropEvent_iff_no_strict_rank_drop (B : AffineBlock) (π : ScanRule) + (X : Cantor) : + X ∈ noDropEvent B π ↔ + ∀ n, ¬B.remainingRank π (π.transcript X (n + 1)) < + B.remainingRank π (π.transcript X n) := by + constructor + · intro h n + rw [(B.unreadFullRank_iff_remainingRank π _).mp (h (n + 1)), + (B.unreadFullRank_iff_remainingRank π _).mp (h n)] + exact lt_irrefl _ + · intro h n + exact (B.unreadFullRank_iff_remainingRank π _).mpr + (B.remainingRank_eq_rank_of_no_drop π X n (fun k _ => h k)) + +/-- This is the event `T = ∞`: no finite first rank drop occurs. -/ +theorem noDropEvent_eq_compl_rankDropTailEvent (B : AffineBlock) (π : ScanRule) : + noDropEvent B π = (rankDropTailEvent B π 0)ᶜ := by + classical + rw [← unionEvent_rankDropTriggerTail] + have htail : firstTriggerTail (rankDropTrigger B π) 0 = + firstTrigger (rankDropTrigger B π) := by + ext v + simp [firstTriggerTail] + rw [htail] + ext X + change (∀ n, B.UnreadFullRank π (π.transcript X n)) ↔ + X ∉ unionEvent π (firstTrigger (rankDropTrigger B π)) + rw [mem_unionEvent_firstTrigger_iff] + constructor + · intro h ⟨n, hn⟩ + exact ((rankDropTrigger_transcript_iff B π X n).mp hn).2 (h (n + 1)) + · intro h n + induction n with + | zero => simpa using B.unreadFullRank_nil π + | succ n ih => + by_contra hbad + exact h ⟨n, (rankDropTrigger_transcript_iff B π X n).mpr ⟨ih, hbad⟩⟩ + +/-- The actual old and new stage laws agree on every finite-horizon surviving cylinder. -/ +theorem nextStage_inputEvent_inter_survival {κ : Type*} [Finite κ] + (old : κ → AffineBlock) (B : AffineBlock) + (hold : Pairwise (fun i j => Disjoint (old i).support (old j).support)) + (hnew : ∀ k, Disjoint (old k).support B.support) + (π : ScanRule) (v : List Bool) (n : ℕ) (hn : v.length ≤ n) : + (cond fairCoin (AffineBlock.familyEvent old ∩ B.event)) + (inputEvent π v ∩ survivalEvent B π n) = + (AffineBlock.finiteStageLaw old) (inputEvent π v ∩ survivalEvent B π n) := by + rw [inputEvent_inter_survival_eq_union B π v n hn] + exact nextStage_unionEvent old B hold hnew π + (survivingExtensions_prefixFree B π v n) (fun _ hw => hw.2.2) + +/-- The no-drop part of a cylinder is the decreasing limit of its surviving refinements. -/ +theorem inputEvent_inter_noDrop_eq_iInter (B : AffineBlock) (π : ScanRule) (v : List Bool) : + inputEvent π v ∩ noDropEvent B π = + ⋂ n, inputEvent π v ∩ survivalEvent B π (n + v.length) := by + ext X + constructor + · rintro ⟨hv, hfull⟩ + exact Set.mem_iInter.mpr (fun n => ⟨hv, hfull _⟩) + · intro h + have h' := Set.mem_iInter.mp h + refine ⟨(h' 0).1, ?_⟩ + intro n + exact survivalEvent_antitone B π (Nat.le_add_right n v.length) (h' n).2 + +/-- Continuity from above extends the finite-stage identity to each no-drop cylinder. -/ +theorem nextStage_inputEvent_inter_noDrop {κ : Type*} [Finite κ] + (old : κ → AffineBlock) (B : AffineBlock) + (hold : Pairwise (fun i j => Disjoint (old i).support (old j).support)) + (hnew : ∀ k, Disjoint (old k).support B.support) + (π : ScanRule) (v : List Bool) : + (cond fairCoin (AffineBlock.familyEvent old ∩ B.event)) + (inputEvent π v ∩ noDropEvent B π) = + (AffineBlock.finiteStageLaw old) (inputEvent π v ∩ noDropEvent B π) := by + have ha : Antitone (fun n => inputEvent π v ∩ survivalEvent B π (n + v.length)) := by + intro m n h X hX + exact ⟨hX.1, survivalEvent_antitone B π (Nat.add_le_add_right h _) hX.2⟩ + have hm (n : ℕ) : MeasurableSet (inputEvent π v ∩ survivalEvent B π (n + v.length)) := + (measurableSet_inputEvent π v).inter (measurableSet_survivalEvent B π _) + let : IsFiniteMeasure (AffineBlock.finiteStageLaw old) := by + unfold AffineBlock.finiteStageLaw + infer_instance + rw [inputEvent_inter_noDrop_eq_iInter, + ha.measure_iInter (fun n => (hm n).nullMeasurableSet) ⟨0, measure_ne_top _ _⟩, + ha.measure_iInter (fun n => (hm n).nullMeasurableSet) ⟨0, measure_ne_top _ _⟩] + exact iInf_congr fun n => nextStage_inputEvent_inter_survival old B hold hnew π v + (n + v.length) (Nat.le_add_left _ _) + +/-- Push forward the actual input measure after restricting it to inputs with no rank drop. -/ +noncomputable def restrictedTranscriptLaw (μ : Measure Cantor) (B : AffineBlock) + (π : ScanRule) : Measure Cantor := + (μ.restrict (noDropEvent B π)).map π.observationMap + +instance (μ : Measure Cantor) [IsFiniteMeasure μ] (B : AffineBlock) (π : ScanRule) : + IsFiniteMeasure (restrictedTranscriptLaw μ B π) := by + unfold restrictedTranscriptLaw + infer_instance + +/-- The no-drop restriction can equivalently be taken after pushing forward to transcripts. -/ +theorem restrictedTranscriptLaw_eq_restrict_map (μ : Measure Cantor) (B : AffineBlock) + (π : ScanRule) : + restrictedTranscriptLaw μ B π = + (μ.map π.observationMap).restrict (noDropTranscripts B π) := by + rw [Measure.restrict_map π.measurable_observationMap (measurableSet_noDropTranscripts B π), + observationMap_preimage_noDropTranscripts] + rfl + +theorem restrictedTranscriptLaw_apply (μ : Measure Cantor) (B : AffineBlock) + (π : ScanRule) {F : Set Cantor} (hF : MeasurableSet F) : + restrictedTranscriptLaw μ B π F = μ (π.observationMap ⁻¹' F ∩ noDropEvent B π) := by + rw [restrictedTranscriptLaw, Measure.map_apply π.measurable_observationMap hF, + Measure.restrict_apply (π.measurable_observationMap hF)] + +/-- Equality of the two finite-stage transcript measures restricted to `T = ∞`. +The identity on cylinders is derived from the block rank condition, not assumed. -/ +theorem nextStage_restrictedTranscriptLaw {κ : Type*} [Finite κ] + (old : κ → AffineBlock) (B : AffineBlock) + (hold : Pairwise (fun i j => Disjoint (old i).support (old j).support)) + (hnew : ∀ k, Disjoint (old k).support B.support) (π : ScanRule) : + restrictedTranscriptLaw (cond fairCoin (AffineBlock.familyEvent old ∩ B.event)) B π = + restrictedTranscriptLaw (AffineBlock.finiteStageLaw old) B π := by + apply measure_eq_of_cylinders + intro v + rw [restrictedTranscriptLaw_apply _ _ _ (measurableSet_cylinder v), + restrictedTranscriptLaw_apply _ _ _ (measurableSet_cylinder v), + π.observationMap_preimage_cylinder] + exact nextStage_inputEvent_inter_noDrop old B hold hnew π v + +/-- The Section 6 no-drop identity as equality of restrictions of the two actual +infinite transcript laws. -/ +theorem nextStage_map_restrict_noDrop {κ : Type*} [Finite κ] + (old : κ → AffineBlock) (B : AffineBlock) + (hold : Pairwise (fun i j => Disjoint (old i).support (old j).support)) + (hnew : ∀ k, Disjoint (old k).support B.support) (π : ScanRule) : + ((cond fairCoin (AffineBlock.familyEvent old ∩ B.event)).map π.observationMap).restrict + (noDropTranscripts B π) = + ((AffineBlock.finiteStageLaw old).map π.observationMap).restrict (noDropTranscripts B π) := by + rw [← restrictedTranscriptLaw_eq_restrict_map, ← restrictedTranscriptLaw_eq_restrict_map] + exact nextStage_restrictedTranscriptLaw old B hold hnew π + +/-- For every Borel transcript event `F`, the old and new stage laws give the same mass +to `F ∩ {T = ∞}`, interpreted through the actual infinite transcript map. -/ +theorem nextStage_noDrop_borel {κ : Type*} [Finite κ] + (old : κ → AffineBlock) (B : AffineBlock) + (hold : Pairwise (fun i j => Disjoint (old i).support (old j).support)) + (hnew : ∀ k, Disjoint (old k).support B.support) (π : ScanRule) + {F : Set Cantor} (hF : MeasurableSet F) : + (cond fairCoin (AffineBlock.familyEvent old ∩ B.event)) + (π.observationMap ⁻¹' F ∩ noDropEvent B π) = + (AffineBlock.finiteStageLaw old) (π.observationMap ⁻¹' F ∩ noDropEvent B π) := by + have h := congrArg (fun μ : Measure Cantor => μ F) + (nextStage_restrictedTranscriptLaw old B hold hnew π) + simpa only [restrictedTranscriptLaw_apply _ _ _ hF] using h + +end NoDrop + +end Klr diff --git a/LeanPool/KLRandomness/Normalization.lean b/LeanPool/KLRandomness/Normalization.lean new file mode 100644 index 0000000000..4fd0dec72b --- /dev/null +++ b/LeanPool/KLRandomness/Normalization.lean @@ -0,0 +1,133 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import Mathlib.Algebra.BigOperators.Group.Finset.Basic +public import Mathlib.Basic.Real.Basic +public import Mathlib.Topology.Algebra.InfiniteSum.Real +public import Mathlib.Tactic.FieldSimp +public import Mathlib.Tactic.Linarith +public import Mathlib.Tactic.Positivity +public import Mathlib.Tactic.Ring +import Mathlib.Tactic.FieldSimp +import Mathlib.Tactic.Linarith +import Mathlib.Tactic.Positivity +import Mathlib.Tactic.Ring + +/-! +# A deterministic bound for normalized wager fractions + +This file proves the pathwise quadratic-variation estimate in Lemma 2 of +Liu and Meng, *Separating Kolmogorov–Loveland randomness from Martin-Löf +randomness*, arXiv:2611.31004v1, pp. 4–5. + +For wager fractions `f t`, write `Q n = ∑ t < n, (f t)^2` and replace the next +fraction by `f n / (2 * (1 + Q n))`. The sum of the squares of the replacement +fractions is at most `1 / 2`. The proof gives the stronger finite telescoping +bound with remainder `1 / (2 * (1 + Q n))`, and then passes to the infinite sum. + +This is an analytic estimate for real sequences. It does not yet assert that the +normalization preserves success or that a strategy computing these fractions is +computable. +-/ + +@[expose] public section + +namespace Klr + +open scoped BigOperators + +/-- The sum of squared wager fractions strictly before time `n`. -/ +def quadraticVariation (f : ℕ → ℝ) (n : ℕ) : ℝ := + ∑ t ∈ Finset.range n, (f t) ^ 2 + +/-- The damping of wager fractions used in Lemma 2 of the paper. -/ +noncomputable def normalizedWager (f : ℕ → ℝ) (n : ℕ) : ℝ := + f n / (2 * (1 + quadraticVariation f n)) + +@[simp] +theorem quadraticVariation_zero (f : ℕ → ℝ) : quadraticVariation f 0 = 0 := by + simp [quadraticVariation] + +@[simp] +theorem quadraticVariation_succ (f : ℕ → ℝ) (n : ℕ) : + quadraticVariation f (n + 1) = quadraticVariation f n + (f n) ^ 2 := by + simp [quadraticVariation, Finset.sum_range_succ] + +theorem quadraticVariation_nonneg (f : ℕ → ℝ) (n : ℕ) : + 0 ≤ quadraticVariation f n := by + exact Finset.sum_nonneg fun t _ ↦ sq_nonneg (f t) + +/-- The one-step inequality underlying the telescoping estimate. -/ +theorem normalized_square_le_telescope (q x : ℝ) (hq : 0 ≤ q) (hx : x ^ 2 ≤ 1) : + (x / (2 * (1 + q))) ^ 2 ≤ + (1 / 2 : ℝ) * (1 / (1 + q) - 1 / (1 + (q + x ^ 2))) := by + have ha : 0 < 1 + q := by linarith + have hb : 0 < 1 + q + x ^ 2 := by positivity + have hproduct : 0 ≤ 2 * (1 + q) * (x ^ 2 * ((1 + q) - x ^ 2)) := by + apply mul_nonneg (by positivity) + exact mul_nonneg (sq_nonneg x) (by linarith) + have hfrac : x ^ 2 / (4 * (1 + q) ^ 2) ≤ + x ^ 2 / (2 * (1 + q) * (1 + q + x ^ 2)) := by + apply (div_le_div_iff₀ (by positivity) (by positivity)).2 + nlinarith only [hproduct] + calc + (x / (2 * (1 + q))) ^ 2 = x ^ 2 / (4 * (1 + q) ^ 2) := by + field_simp + ring + _ ≤ x ^ 2 / (2 * (1 + q) * (1 + q + x ^ 2)) := hfrac + _ = (1 / 2 : ℝ) * (1 / (1 + q) - 1 / (1 + (q + x ^ 2))) := by + field_simp + ring + +theorem normalizedWager_sq_le_telescope (f : ℕ → ℝ) (n : ℕ) + (hf : (f n) ^ 2 ≤ 1) : + (normalizedWager f n) ^ 2 ≤ + (1 / 2 : ℝ) * (1 / (1 + quadraticVariation f n) - + 1 / (1 + quadraticVariation f (n + 1))) := by + simpa only [normalizedWager, quadraticVariation_succ] using + normalized_square_le_telescope (quadraticVariation f n) (f n) + (quadraticVariation_nonneg f n) hf + +/-- A stronger finite estimate, retaining the nonnegative telescoping remainder. -/ +theorem sum_normalizedWager_sq_le_telescope (f : ℕ → ℝ) + (hf : ∀ t, (f t) ^ 2 ≤ 1) (n : ℕ) : + (∑ t ∈ Finset.range n, (normalizedWager f t) ^ 2) ≤ + (1 / 2 : ℝ) * (1 - 1 / (1 + quadraticVariation f n)) := by + induction n with + | zero => simp + | succ n ih => + rw [Finset.sum_range_succ] + have hstep := normalizedWager_sq_le_telescope f n (hf n) + linarith + +/-- The pathwise bound in equation (2), for every finite initial segment. -/ +theorem sum_normalizedWager_sq_le_half (f : ℕ → ℝ) + (hf : ∀ t, (f t) ^ 2 ≤ 1) (n : ℕ) : + (∑ t ∈ Finset.range n, (normalizedWager f t) ^ 2) ≤ (1 / 2 : ℝ) := by + have htel := sum_normalizedWager_sq_le_telescope f hf n + have hnonneg : 0 ≤ 1 / (1 + quadraticVariation f n) := by + have := quadraticVariation_nonneg f n + positivity + linarith + +/-- The replacement fractions are square-summable on every path. -/ +theorem summable_normalizedWager_sq (f : ℕ → ℝ) + (hf : ∀ t, |f t| ≤ 1) : Summable (fun t ↦ (normalizedWager f t) ^ 2) := by + apply summable_of_sum_range_le (c := (1 / 2 : ℝ)) (fun t ↦ sq_nonneg _) + exact sum_normalizedWager_sq_le_half f (fun t ↦ (sq_le_one_iff_abs_le_one _).2 (hf t)) + +/-- The infinite-series bound in equation (2) of the paper. -/ +theorem tsum_normalizedWager_sq_le_half (f : ℕ → ℝ) + (hf : ∀ t, |f t| ≤ 1) : + (∑' t, (normalizedWager f t) ^ 2) ≤ (1 / 2 : ℝ) := by + apply Real.tsum_le_of_sum_range_le (fun t ↦ sq_nonneg _) + exact sum_normalizedWager_sq_le_half f (fun t ↦ (sq_le_one_iff_abs_le_one _).2 (hf t)) + +end Klr diff --git a/LeanPool/KLRandomness/NormalizationSuccess.lean b/LeanPool/KLRandomness/NormalizationSuccess.lean new file mode 100644 index 0000000000..0b2ee5bac0 --- /dev/null +++ b/LeanPool/KLRandomness/NormalizationSuccess.lean @@ -0,0 +1,421 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.Normalization +public import Mathlib.Analysis.SpecialFunctions.Log.Basic +import Mathlib.Tactic.FieldSimp +import Mathlib.Tactic.Linarith +import Mathlib.Tactic.NormNum +import Mathlib.Tactic.Positivity +import Mathlib.Tactic.Ring + +/-! +# Deterministic preservation of success + +The second half of Lemma 2 in Liu and Meng, arXiv:2611.31004v1, uses Abel +summation to show that damping wagers preserves unbounded capital, provided +the original capital has first been kept above a positive reserve. + +The main theorem `normalization_preserves_unbounded_capital` proves this +pathwise statement for real signed returns. Original and normalized capital +are the products of `1 + x t` and `1 + normalizedWager x t`, respectively. +The preceding file proves the uniform square-sum bound. Together they verify +the analytic damping step of Lemma 2; constructing the positive rational +reserve strategy and proving computability are separate tasks. + +The estimates below use the sufficient bound +`log (1 + x) ≤ x - x^2 / 6` for `-1 < x ≤ 1`; the paper uses the sharper +constant `1 / 4`. The weaker constant admits an elementary proof from +`log y ≤ y - 1` and does not change the normalization. +-/ + +@[expose] public section + +namespace Klr + +open scoped BigOperators + +/-- The cumulative signed return before time `n`. -/ +def prefixReturn (x : ℕ → ℝ) (n : ℕ) : ℝ := ∑ t ∈ Finset.range n, x t + +/-- A cumulative return with a weight chosen before each step. -/ +def weightedReturn (a x : ℕ → ℝ) (n : ℕ) : ℝ := + ∑ t ∈ Finset.range n, a t * x t + +@[simp] theorem prefixReturn_zero (x : ℕ → ℝ) : prefixReturn x 0 = 0 := by + simp [prefixReturn] + +@[simp] theorem prefixReturn_succ (x : ℕ → ℝ) (n : ℕ) : + prefixReturn x (n + 1) = prefixReturn x n + x n := by + simp [prefixReturn, Finset.sum_range_succ] + +@[simp] theorem weightedReturn_zero (a x : ℕ → ℝ) : weightedReturn a x 0 = 0 := by + simp [weightedReturn] + +@[simp] theorem weightedReturn_succ (a x : ℕ → ℝ) (n : ℕ) : + weightedReturn a x (n + 1) = weightedReturn a x n + a n * x n := by + simp [weightedReturn, Finset.sum_range_succ] + +/-- Abel summation with a terminal coefficient at `n`, avoiding subtraction on naturals. -/ +theorem weightedReturn_abel (a x : ℕ → ℝ) (n : ℕ) : + weightedReturn a x n = a n * prefixReturn x n + + ∑ t ∈ Finset.range n, (a t - a (t + 1)) * prefixReturn x (t + 1) := by + induction n with + | zero => simp + | succ n ih => + rw [weightedReturn_succ, Finset.sum_range_succ, ih, prefixReturn_succ] + ring + +theorem abel_coefficient_sum (a : ℕ → ℝ) (n : ℕ) : + a n + (∑ t ∈ Finset.range n, (a t - a (t + 1))) = a 0 := by + induction n with + | zero => simp + | succ n ih => + rw [Finset.sum_range_succ] + linarith + +/-- Decreasing weights preserve a lower bound for cumulative returns, including +the contribution of the terminal cumulative return. -/ +theorem weightedReturn_lower_bound (a x : ℕ → ℝ) (c : ℝ) + (ha : ∀ t, a (t + 1) ≤ a t) (hx : ∀ t, c ≤ prefixReturn x t) (n : ℕ) : + a n * (prefixReturn x n - c) + c * a 0 ≤ weightedReturn a x n := by + have hsum : (∑ t ∈ Finset.range n, (a t - a (t + 1))) * c ≤ + ∑ t ∈ Finset.range n, (a t - a (t + 1)) * prefixReturn x (t + 1) := by + rw [Finset.sum_mul] + exact Finset.sum_le_sum fun t _ ↦ + mul_le_mul_of_nonneg_left (hx (t + 1)) (sub_nonneg.mpr (ha t)) + have hcoef := congrArg (fun z : ℝ ↦ z * c) (abel_coefficient_sum a n) + rw [weightedReturn_abel] + nlinarith + +theorem weightedReturn_ge_initial (a x : ℕ → ℝ) (c : ℝ) + (ha : ∀ t, a (t + 1) ≤ a t) (ha0 : ∀ t, 0 ≤ a t) + (hx : ∀ t, c ≤ prefixReturn x t) (n : ℕ) : + c * a 0 ≤ weightedReturn a x n := by + have h := weightedReturn_lower_bound a x c ha hx n + have hnonneg := mul_nonneg (ha0 n) (sub_nonneg.mpr (hx n)) + linarith + +/-- An elementary quadratic upper estimate sufficient for preservation of success. -/ +theorem log_one_add_le_sub_sq_sixth (x : ℝ) (hx0 : -1 < x) (hx1 : x ≤ 1) : + Real.log (1 + x) ≤ x - x ^ 2 / 6 := by + have h1 : 0 < 1 + x := by linarith + have h2 : 0 < 1 + x / 2 := by linarith + have h3 : 0 < 2 + x := by linarith + have hlog1 := Real.log_le_sub_one_of_pos h2 + have hlog2 := Real.log_le_sub_one_of_pos (div_pos h1 h2) + rw [Real.log_div (ne_of_gt h1) (ne_of_gt h2)] at hlog2 + have hrat : (1 + x / 2) - 1 + ((1 + x) / (1 + x / 2) - 1) = + x - x ^ 2 / (2 * (2 + x)) := by + field_simp + ring + have hden : 0 < 2 * (2 + x) := by positivity + have hsq : x ^ 2 / 6 ≤ x ^ 2 / (2 * (2 + x)) := by + apply div_le_div_of_nonneg_left (sq_nonneg x) hden + linarith + linarith + +/-- On the interval used by the damped strategy, logarithms lose at most twice +the squared wager. -/ +theorem sub_two_sq_le_log_one_add (x : ℝ) (hx : |x| ≤ (1 / 2 : ℝ)) : + x - 2 * x ^ 2 ≤ Real.log (1 + x) := by + obtain ⟨hlo, hhi⟩ := abs_le.mp hx + have hpos : 0 < 1 + x := by linarith + have hlog := Real.one_sub_inv_le_log_of_pos hpos + have hrat : 1 - (1 + x)⁻¹ = x - x ^ 2 / (1 + x) := by + field_simp + ring + have hsq : x ^ 2 / (1 + x) ≤ 2 * x ^ 2 := by + apply (div_le_iff₀ hpos).2 + nlinarith [mul_nonneg (sq_nonneg x) (by linarith : 0 ≤ 1 + 2 * x)] + linarith + +/-- The positive, decreasing weight chosen from the original quadratic variation. -/ +noncomputable def damping (x : ℕ → ℝ) (n : ℕ) : ℝ := + 1 / (2 * (1 + quadraticVariation x n)) + +@[simp] theorem damping_zero (x : ℕ → ℝ) : damping x 0 = (1 / 2 : ℝ) := by + simp [damping] + +theorem damping_pos (x : ℕ → ℝ) (n : ℕ) : 0 < damping x n := by + have := quadraticVariation_nonneg x n + unfold damping + positivity + +theorem damping_succ_le (x : ℕ → ℝ) (n : ℕ) : damping x (n + 1) ≤ damping x n := by + have hq := quadraticVariation_nonneg x n + unfold damping + apply one_div_le_one_div_of_le (by positivity) + rw [quadraticVariation_succ] + nlinarith [sq_nonneg (x n)] + +theorem normalizedWager_eq_damping_mul (x : ℕ → ℝ) (n : ℕ) : + normalizedWager x n = damping x n * x n := by + simp [normalizedWager, damping, div_eq_mul_inv, mul_comm] + +theorem weightedReturn_damping (x : ℕ → ℝ) (n : ℕ) : + weightedReturn (damping x) x n = prefixReturn (normalizedWager x) n := by + simp [weightedReturn, prefixReturn, normalizedWager_eq_damping_mul] + +theorem weightedReturn_sub_mul (a x y : ℕ → ℝ) (k : ℝ) (n : ℕ) : + weightedReturn a (fun t ↦ x t - k * y t) n = + weightedReturn a x n - k * weightedReturn a y n := by + simp only [weightedReturn, mul_sub, Finset.sum_sub_distrib] + rw [Finset.mul_sum] + congr 1 + apply Finset.sum_congr rfl + intro t _ + ring + +theorem prefixReturn_sub_sq (x : ℕ → ℝ) (k : ℝ) (n : ℕ) : + prefixReturn (fun t ↦ x t - k * (x t) ^ 2) n = + prefixReturn x n - k * quadraticVariation x n := by + simp [prefixReturn, quadraticVariation, Finset.sum_sub_distrib, Finset.mul_sum] + +/-- Abel summation transfers a quadratic lower envelope of the cumulative return +to a lower bound for the weighted cumulative return. -/ +theorem weightedReturn_damping_lower_envelope (x : ℕ → ℝ) (c k : ℝ) + (hx : ∀ n, c + k * quadraticVariation x n ≤ prefixReturn x n) (n : ℕ) : + c / 2 + k * weightedReturn (damping x) (fun t ↦ (x t) ^ 2) n ≤ + weightedReturn (damping x) x n := by + have hadj : ∀ t, c ≤ prefixReturn (fun s ↦ x s - k * (x s) ^ 2) t := by + intro t + rw [prefixReturn_sub_sq] + linarith [hx t] + have h := weightedReturn_ge_initial (damping x) (fun t ↦ x t - k * (x t) ^ 2) + c (damping_succ_le x) (fun t ↦ (damping_pos x t).le) hadj n + rw [weightedReturn_sub_mul, damping_zero] at h + linarith + +theorem log_quadraticVariation_step_le (x : ℕ → ℝ) (n : ℕ) : + Real.log (1 + quadraticVariation x (n + 1)) - + Real.log (1 + quadraticVariation x n) ≤ (x n) ^ 2 / (1 + quadraticVariation x n) := by + have hq := quadraticVariation_nonneg x n + have hq' := quadraticVariation_nonneg x (n + 1) + have ha : 0 < 1 + quadraticVariation x n := by positivity + have hb : 0 < 1 + quadraticVariation x (n + 1) := by positivity + have h := Real.log_le_sub_one_of_pos (div_pos hb ha) + rw [Real.log_div (ne_of_gt hb) (ne_of_gt ha)] at h + have heq : (1 + quadraticVariation x (n + 1)) / (1 + quadraticVariation x n) - 1 = + (x n) ^ 2 / (1 + quadraticVariation x n) := by + rw [quadraticVariation_succ] + field_simp + ring + rwa [heq] at h + +/-- A finite logarithmic bound, without invoking convergence of any series. -/ +theorem log_quadraticVariation_le_weighted_squares (x : ℕ → ℝ) (n : ℕ) : + Real.log (1 + quadraticVariation x n) ≤ + 2 * weightedReturn (damping x) (fun t ↦ (x t) ^ 2) n := by + induction n with + | zero => simp + | succ n ih => + rw [weightedReturn_succ] + have hstep := log_quadraticVariation_step_le x n + have hterm : (x n) ^ 2 / (1 + quadraticVariation x n) = + 2 * (damping x n * (x n) ^ 2) := by + simp [damping] + ring + rw [hterm] at hstep + linarith + +theorem weightedReturn_damping_log_lower_bound (x : ℕ → ℝ) (c k : ℝ) (hk : 0 ≤ k) + (hx : ∀ n, c + k * quadraticVariation x n ≤ prefixReturn x n) (n : ℕ) : + c / 2 + (k / 2) * Real.log (1 + quadraticVariation x n) ≤ + weightedReturn (damping x) x n := by + have he := weightedReturn_damping_lower_envelope x c k hx n + have hl := mul_le_mul_of_nonneg_left + (log_quadraticVariation_le_weighted_squares x n) hk + linarith + +/-- With bounded quadratic variation, the damping weights stay uniformly positive. -/ +theorem weightedReturn_damping_lower_bound_of_variation_le (x : ℕ → ℝ) (c b : ℝ) + (hxb : ∀ n, quadraticVariation x n ≤ b) + (hx : ∀ n, c ≤ prefixReturn x n) (n : ℕ) : + (1 / (2 * (1 + b))) * (prefixReturn x n - c) + c / 2 ≤ + weightedReturn (damping x) x n := by + have hweight : 1 / (2 * (1 + b)) ≤ damping x n := by + unfold damping + apply one_div_le_one_div_of_le + · have := quadraticVariation_nonneg x n + positivity + · linarith [hxb n] + have h := weightedReturn_lower_bound (damping x) x c (damping_succ_le x) hx n + rw [damping_zero] at h + have hm := mul_le_mul_of_nonneg_right hweight (sub_nonneg.mpr (hx n)) + linarith + +/-- Under a positive quadratic lower envelope, bounding the damped cumulative +return bounds the original cumulative return. This packages both cases of the +paper's Abel-summation argument into a single implication. -/ +theorem bddAbove_prefixReturn_of_bddAbove_dampedReturn (x : ℕ → ℝ) (c k : ℝ) + (hk : 0 < k) (hx : ∀ n, c + k * quadraticVariation x n ≤ prefixReturn x n) + (hbound : BddAbove (Set.range (weightedReturn (damping x) x))) : + BddAbove (Set.range (prefixReturn x)) := by + rcases hbound with ⟨a, ha⟩ + have hA : ∀ n, weightedReturn (damping x) x n ≤ a := fun n ↦ ha (Set.mem_range_self n) + let b := Real.exp ((2 * a - c) / k) + have hb : 0 < b := Real.exp_pos _ + have hQ : ∀ n, quadraticVariation x n ≤ b := by + intro n + have hl := weightedReturn_damping_log_lower_bound x c k hk.le hx n + have hlog : Real.log (1 + quadraticVariation x n) ≤ (2 * a - c) / k := by + apply (le_div_iff₀ hk).2 + linarith [hA n] + have hq := quadraticVariation_nonneg x n + have hexp := (Real.log_le_iff_le_exp (by positivity : 0 < 1 + quadraticVariation x n)).1 hlog + change 1 + quadraticVariation x n ≤ b at hexp + linarith + have hM : ∀ n, c ≤ prefixReturn x n := by + intro n + have := mul_nonneg hk.le (quadraticVariation_nonneg x n) + linarith [hx n] + let d : ℝ := 1 / (2 * (1 + b)) + have hd : 0 < d := by unfold d; positivity + refine ⟨c + (a - c / 2) / d, ?_⟩ + rintro _ ⟨n, rfl⟩ + have hl := weightedReturn_damping_lower_bound_of_variation_le x c b hQ hM n + change d * (prefixReturn x n - c) + c / 2 ≤ weightedReturn (damping x) x n at hl + have hh : prefixReturn x n - c ≤ (a - c / 2) / d := by + apply (le_div_iff₀ hd).2 + nlinarith [hA n] + linarith + +/-- Capital starting at one and updated by the signed multiplicative returns `x t`. -/ +def multiplicativeCapital (x : ℕ → ℝ) (n : ℕ) : ℝ := + ∏ t ∈ Finset.range n, (1 + x t) + +@[simp] theorem multiplicativeCapital_zero (x : ℕ → ℝ) : multiplicativeCapital x 0 = 1 := by + simp [multiplicativeCapital] + +@[simp] theorem multiplicativeCapital_succ (x : ℕ → ℝ) (n : ℕ) : + multiplicativeCapital x (n + 1) = multiplicativeCapital x n * (1 + x n) := by + simp [multiplicativeCapital, Finset.prod_range_succ] + +theorem multiplicativeCapital_pos (x : ℕ → ℝ) (hx : ∀ t, -1 < x t) (n : ℕ) : + 0 < multiplicativeCapital x n := by + apply Finset.prod_pos + intro t _ + linarith [hx t] + +theorem log_multiplicativeCapital_le (x : ℕ → ℝ) + (hx0 : ∀ t, -1 < x t) (hx1 : ∀ t, x t ≤ 1) (n : ℕ) : + Real.log (multiplicativeCapital x n) ≤ prefixReturn x n - quadraticVariation x n / 6 := by + induction n with + | zero => simp + | succ n ih => + rw [multiplicativeCapital_succ, Real.log_mul (ne_of_gt (multiplicativeCapital_pos x hx0 n)) + (by linarith [hx0 n]), prefixReturn_succ, quadraticVariation_succ] + have hs := log_one_add_le_sub_sq_sixth (x n) (hx0 n) (hx1 n) + linarith + +theorem normalizedWager_abs_le_half (x : ℕ → ℝ) (hx : ∀ t, |x t| ≤ 1) (n : ℕ) : + |normalizedWager x n| ≤ (1 / 2 : ℝ) := by + have hq := quadraticVariation_nonneg x n + have hden : 0 < 2 * (1 + quadraticVariation x n) := by positivity + rw [normalizedWager, abs_div, abs_of_pos hden] + apply (div_le_iff₀ hden).2 + linarith [hx n] + +theorem normalizedWager_gt_neg_one (x : ℕ → ℝ) (hx : ∀ t, |x t| ≤ 1) (n : ℕ) : + -1 < normalizedWager x n := by + have := (abs_le.mp (normalizedWager_abs_le_half x hx n)).1 + linarith + +theorem sub_two_quadraticVariation_le_log_capital (x : ℕ → ℝ) + (hx : ∀ t, |x t| ≤ (1 / 2 : ℝ)) (n : ℕ) : + prefixReturn x n - 2 * quadraticVariation x n ≤ Real.log (multiplicativeCapital x n) := by + have hpos : ∀ t, -1 < x t := by + intro t + have := (abs_le.mp (hx t)).1 + linarith + induction n with + | zero => simp + | succ n ih => + rw [multiplicativeCapital_succ, Real.log_mul (ne_of_gt (multiplicativeCapital_pos x hpos n)) + (by linarith [hpos n]), prefixReturn_succ, quadraticVariation_succ] + have hs := sub_two_sq_le_log_one_add (x n) (hx n) + linarith + +/-- The logarithm of normalized capital is within one of the damped cumulative +return. This is the lower capital estimate used in Lemma 2. -/ +theorem dampedReturn_sub_one_le_log_normalizedCapital (x : ℕ → ℝ) + (hx : ∀ t, |x t| ≤ 1) (n : ℕ) : + weightedReturn (damping x) x n - 1 ≤ + Real.log (multiplicativeCapital (normalizedWager x) n) := by + have hl := sub_two_quadraticVariation_le_log_capital (normalizedWager x) + (normalizedWager_abs_le_half x hx) n + have hq := sum_normalizedWager_sq_le_half x + (fun t ↦ (sq_le_one_iff_abs_le_one _).2 (hx t)) n + change quadraticVariation (normalizedWager x) n ≤ (1 / 2 : ℝ) at hq + rw [weightedReturn_damping] + linarith + +theorem bddAbove_dampedReturn_of_bddAbove_normalizedCapital (x : ℕ → ℝ) + (hx : ∀ t, |x t| ≤ 1) + (hbound : BddAbove (Set.range (multiplicativeCapital (normalizedWager x)))) : + BddAbove (Set.range (weightedReturn (damping x) x)) := by + rcases hbound with ⟨b, hb⟩ + refine ⟨Real.log b + 1, ?_⟩ + rintro _ ⟨n, rfl⟩ + have hl := dampedReturn_sub_one_le_log_normalizedCapital x hx n + have hlog := Real.log_le_log + (multiplicativeCapital_pos _ (normalizedWager_gt_neg_one x hx) n) + (hb (Set.mem_range_self n)) + linarith + +/-- A positive reserve turns the logarithmic capital bound into the quadratic +lower envelope needed by Abel summation. -/ +theorem reserve_lower_envelope (x : ℕ → ℝ) (δ : ℝ) + (hx0 : ∀ t, -1 < x t) (hx1 : ∀ t, x t ≤ 1) (hδ : 0 < δ) + (hreserve : ∀ n, δ ≤ multiplicativeCapital x n) (n : ℕ) : + Real.log δ + (1 / 6 : ℝ) * quadraticVariation x n ≤ prefixReturn x n := by + have hl := Real.log_le_log hδ (hreserve n) + have hu := log_multiplicativeCapital_le x hx0 hx1 n + linarith + +theorem bddAbove_capital_of_bddAbove_prefixReturn (x : ℕ → ℝ) + (hx0 : ∀ t, -1 < x t) (hx1 : ∀ t, x t ≤ 1) + (hbound : BddAbove (Set.range (prefixReturn x))) : + BddAbove (Set.range (multiplicativeCapital x)) := by + rcases hbound with ⟨b, hb⟩ + refine ⟨Real.exp b, ?_⟩ + rintro _ ⟨n, rfl⟩ + apply (Real.log_le_iff_le_exp (multiplicativeCapital_pos x hx0 n)).1 + have hu := log_multiplicativeCapital_le x hx0 hx1 n + have hq := quadraticVariation_nonneg x n + linarith [hb (Set.mem_range_self n)] + +/-- If reserved original capital were unbounded, the normalized capital could +not be bounded. This is the deterministic success-preservation argument of +Lemma 2, stated in its contrapositive form. -/ +theorem bddAbove_capital_of_bddAbove_normalizedCapital (x : ℕ → ℝ) (δ : ℝ) + (hx : ∀ t, |x t| < 1) (hδ : 0 < δ) + (hreserve : ∀ n, δ ≤ multiplicativeCapital x n) + (hbound : BddAbove (Set.range (multiplicativeCapital (normalizedWager x)))) : + BddAbove (Set.range (multiplicativeCapital x)) := by + have hx0 : ∀ t, -1 < x t := fun t ↦ (abs_lt.mp (hx t)).1 + have hx1 : ∀ t, x t ≤ 1 := fun t ↦ (abs_lt.mp (hx t)).2.le + have hA := bddAbove_dampedReturn_of_bddAbove_normalizedCapital x (fun t ↦ (hx t).le) hbound + have hM := bddAbove_prefixReturn_of_bddAbove_dampedReturn x (Real.log δ) (1 / 6) + (by norm_num) (reserve_lower_envelope x δ hx0 hx1 hδ hreserve) hA + exact bddAbove_capital_of_bddAbove_prefixReturn x hx0 hx1 hM + +/-- Damping the signed returns preserves success along any path on which the +original capital stays above a positive reserve. -/ +theorem normalization_preserves_unbounded_capital (x : ℕ → ℝ) (δ : ℝ) + (hx : ∀ t, |x t| < 1) (hδ : 0 < δ) + (hreserve : ∀ n, δ ≤ multiplicativeCapital x n) + (hunbounded : ¬ BddAbove (Set.range (multiplicativeCapital x))) : + ¬ BddAbove (Set.range (multiplicativeCapital (normalizedWager x))) := by + intro hbound + exact hunbounded (bddAbove_capital_of_bddAbove_normalizedCapital x δ hx hδ hreserve hbound) + +end Klr diff --git a/LeanPool/KLRandomness/PairRespecting.lean b/LeanPool/KLRandomness/PairRespecting.lean new file mode 100644 index 0000000000..ace632a76f --- /dev/null +++ b/LeanPool/KLRandomness/PairRespecting.lean @@ -0,0 +1,123 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.Betting + +/-! +# Scans that read the two bits of a digit consecutively + +A pair-respecting scan starts each pair at an even position and reads its odd +partner immediately, independently of the first answer. The hit equivalence +below concerns prescribed answer sequences, as used by the pool construction. +-/ + +@[expose] public section + +namespace Klr + +/-- Reading the two bits of each base-four digit consecutively, even bit first. -/ +def ScanRule.PairRespecting (π : ScanRule) : Prop := + ∀ v : List Bool, v.length % 2 = 0 → + π.query v % 2 = 0 ∧ ∀ b : Bool, π.query (v ++ [b]) = π.query v + 1 + +/-- The strategy scans both bits of each pair consecutively in the prescribed order. -/ +def BettingStrategy.PairRespecting (s : BettingStrategy) : Prop := + s.scan.PairRespecting + +/-- Resistance to the binary strategies that read whole pairs of coordinates. -/ +def PairRespectingRandom (X : Cantor) : Prop := + ∀ s : BettingStrategy, s.PairRespecting → ¬ s.Succeeds X + +theorem ScanRule.monotone_pairRespecting : ScanRule.monotone.PairRespecting := by + intro v hv + refine ⟨hv, ?_⟩ + intro b + simp [ScanRule.monotone] + +theorem KolmogorovLovelandRandom.pairRespectingRandom {X : Cantor} + (hX : KolmogorovLovelandRandom X) : PairRespectingRandom X := + fun s _ => hX s + +namespace ScanRule.PairRespecting + +variable {π : ScanRule} (hπ : π.PairRespecting) + +include hπ + +theorem even_query (Z : Cantor) (n : ℕ) : + π.query (ScanRule.inputPrefix Z (2 * n)) % 2 = 0 := + (hπ _ (by simp [ScanRule.inputPrefix])).1 + +theorem odd_query (Z : Cantor) (n : ℕ) : + π.query (ScanRule.inputPrefix Z (2 * n + 1)) = + π.query (ScanRule.inputPrefix Z (2 * n)) + 1 := by + have hs : ScanRule.inputPrefix Z (2 * n + 1) = + ScanRule.inputPrefix Z (2 * n) ++ [Z (2 * n)] := by + simp [ScanRule.inputPrefix, List.range_succ] + rw [hs] + exact (hπ _ (by simp [ScanRule.inputPrefix])).2 _ + +theorem query_parity (Z : Cantor) (t : ℕ) : + π.query (ScanRule.inputPrefix Z t) % 2 = t % 2 := by + have ht : t = 2 * (t / 2) + t % 2 := by omega + have hmod : t % 2 = 0 ∨ t % 2 = 1 := by omega + rcases hmod with h | h + · have he : t = 2 * (t / 2) := by omega + rw [he] + simpa using hπ.even_query Z (t / 2) + · have he : t = 2 * (t / 2) + 1 := by omega + rw [he, hπ.odd_query] + have hq := hπ.even_query Z (t / 2) + omega + +/-- Both members of a pair are read, or both are missed, on every answer path. +The statement deliberately uses eventual reads; finite horizons may end between +the two members of a pair. -/ +theorem reads_even_iff_reads_odd (Z : Cantor) (n : ℕ) : + (∃ t, π.query (ScanRule.inputPrefix Z t) = 2 * n) ↔ + (∃ t, π.query (ScanRule.inputPrefix Z t) = 2 * n + 1) := by + constructor + · rintro ⟨t, ht⟩ + have hp := hπ.query_parity Z t + have he : t = 2 * (t / 2) := by omega + refine ⟨t + 1, ?_⟩ + rw [he, hπ.odd_query] + rw [← he, ht] + · rintro ⟨t, ht⟩ + have hp := hπ.query_parity Z t + have he : t = 2 * (t / 2) + 1 := by omega + refine ⟨2 * (t / 2), ?_⟩ + rw [he, hπ.odd_query] at ht + omega + +/-- Dividing the query positions by two identifies either bit of a digit. +The divided query tree need not be fresh, since each digit is read twice. -/ +theorem reads_div_two_iff (Z : Cantor) (n c : ℕ) (hc : c < 2) : + (∃ t, π.query (ScanRule.inputPrefix Z t) / 2 = n) ↔ + (∃ t, π.query (ScanRule.inputPrefix Z t) = 2 * n + c) := by + have hc' : c = 0 ∨ c = 1 := by omega + constructor + · rintro ⟨t, ht⟩ + have hq : π.query (ScanRule.inputPrefix Z t) = 2 * n ∨ + π.query (ScanRule.inputPrefix Z t) = 2 * n + 1 := by omega + rcases hc' with rfl | rfl + · simp only [Nat.add_zero] + rcases hq with hq | hq + · exact ⟨t, hq⟩ + · exact (hπ.reads_even_iff_reads_odd Z n).mpr ⟨t, hq⟩ + · rcases hq with hq | hq + · exact (hπ.reads_even_iff_reads_odd Z n).mp ⟨t, hq⟩ + · exact ⟨t, hq⟩ + · rintro ⟨t, ht⟩ + exact ⟨t, by omega⟩ + +end ScanRule.PairRespecting + +end Klr diff --git a/LeanPool/KLRandomness/ParityConstruction.lean b/LeanPool/KLRandomness/ParityConstruction.lean new file mode 100644 index 0000000000..c625b36f27 --- /dev/null +++ b/LeanPool/KLRandomness/ParityConstruction.lean @@ -0,0 +1,106 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.ParityPools +public import LeanPool.KLRandomness.ConfinedStageConstruction +public import LeanPool.KLRandomness.ParityDescription +public import LeanPool.KLRandomness.StageEnumeration + +/-! +# Defeating pair-respecting strategies with two nonrandom halves + +At stage `n` the affine block uses only coordinates congruent to `n` modulo +two. The common Borel partitions supply both kinds of pools. The resulting +block law defeats every pair-respecting strategy, while each coordinate +half fails its own genuine Martin-Löf test. +-/ + +@[expose] public section + +noncomputable section + +namespace Klr.ParityConstruction + +open MeasureTheory + +/-- The complete stage construction with alternating even and odd supports. -/ +theorem exists_sequence (s : ℕ → BettingStrategy) + (hs : ∀ i, (s i).PairRespecting) : + ∃ (H : ℕ → Set Cantor) (B : ℕ → AffineBlock) (V : ℕ → ℕ), + (∀ i, MeasurableSet (H i)) ∧ + Pairwise (fun i j => Disjoint (B i).support (B j).support) ∧ + (∀ n, ∀ p ∈ (B n).support, p % 2 = n % 2) ∧ + (∀ i, StageEstimates B (s i).normalize.scan + (s i).normalize.capital.wager V (H i) i) ∧ + ∀ n : ℕ, ∃ (p : List Bool) (c : AffineCode.Data), + c ∈ AffineDescription.run p ∧ AffineCode.valid c = true ∧ + 2 * p.length + n + 1 ≤ AffineCode.rank c ∧ AffineCode.event c = (B n).event := by + obtain ⟨H, hH, hpools⟩ := ParityPools.exists_fixed_partitions_parity_pools + (fun i => (s i).normalize.scan) (fun i => by + rw [BettingStrategy.normalize_scan] + exact hs i) + have hp : ConfinedStageConstruction.PoolSupply s H + (fun n p => p % 2 = n % 2) := by + intro n η hη z + exact hpools (n + 1) η hη z (n % 2) (Nat.mod_lt _ (by decide)) + obtain ⟨B, V, hd, hc, he, hp⟩ := + ConfinedStageConstruction.exists_sequence s H hH (fun n p => p % 2 = n % 2) hp + exact ⟨H, B, V, hH, hd, hc, he, hp⟩ + +/-- Only a classical covering enumeration of the pair-respecting subtype is +used. No effective enumeration of all total strategies is required. -/ +theorem exists_surjective : + ∃ s : ℕ → {t : BettingStrategy // t.PairRespecting}, Function.Surjective s := by + classical + let : Encodable {t : BettingStrategy // t.PairRespecting} := Encodable.ofCountable _ + let idle : {t : BettingStrategy // t.PairRespecting} := + ⟨StageEnumeration.idle, ScanRule.monotone_pairRespecting⟩ + let s (n : ℕ) : {t : BettingStrategy // t.PairRespecting} := + (Encodable.decode n).getD idle + refine ⟨s, fun t => ⟨Encodable.encode t, ?_⟩⟩ + simp [s] + +/-- Alternating parity blocks yield a sequence resisting every pair-respecting +strategy while both halves fail Martin-Löf randomness. -/ +theorem exists_pairRespectingRandom_halves_not_martinLofRandom : + ∃ X : Cantor, PairRespectingRandom X ∧ + ¬MartinLofRandom (fun n => X (2 * n)) ∧ + ¬MartinLofRandom (fun n => X (2 * n + 1)) := by + obtain ⟨s, hs⟩ := exists_surjective + obtain ⟨H, B, V, _, hdis, hparity, hest, hprogram⟩ := + exists_sequence (fun i => (s i).val) (fun i => (s i).property) + have hfail : ∀ i, ∀ᵐ X ∂BlockProduct.law B hdis, + ¬(s i).val.normalize.Succeeds X := by + intro i + exact BlockRandomness.ae_not_succeeds B hdis (s i).val.normalize + (s i).val.normalize_wager_abs_le_half ((hest i).ae_summable_forcedWager hdis) + have hall : ∀ᵐ X ∂BlockProduct.law B hdis, + ∀ i, ¬(s i).val.normalize.Succeeds X := ae_all_iff.mpr hfail + have hboth : ∀ᵐ X ∂BlockProduct.law B hdis, + PairRespectingRandom X ∧ + ¬MartinLofRandom (fun n => X (2 * n)) ∧ + ¬MartinLofRandom (fun n => X (2 * n + 1)) := by + filter_upwards [hall, BlockProduct.ae_all_blocks B hdis] with X hX hblocks + refine ⟨?_, ?_, ?_⟩ + · intro t ht hsuccess + obtain ⟨i, hi⟩ := hs ⟨t, ht⟩ + have he : (s i).val = t := congrArg Subtype.val hi + exact hX i (he ▸ t.normalize_preserves_success hsuccess) + · have he : ParityDescription.half 0 X = (fun n => X (2 * n)) := by + funext n + simp [ParityDescription.half] + rw [← he] + exact ParityDescription.not_martinLofRandom_half_of_blocks + B hparity hprogram X hblocks 0 + · exact ParityDescription.not_martinLofRandom_half_of_blocks + B hparity hprogram X hblocks 1 + exact hboth.exists + +end Klr.ParityConstruction diff --git a/LeanPool/KLRandomness/ParityDescription.lean b/LeanPool/KLRandomness/ParityDescription.lean new file mode 100644 index 0000000000..3d431fad52 --- /dev/null +++ b/LeanPool/KLRandomness/ParityDescription.lean @@ -0,0 +1,362 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.AffineDescription +public import LeanPool.KLRandomness.StageCodeSearch +import Mathlib.Tactic.FunProp +import Mathlib.Tactic.NormNum +import Mathlib.Tactic.Positivity + +/-! +# Affine-description tests on the two coordinate halves + +A finite truth-table check verifies that an affine event depends only on +one parity of coordinates. Its pullback to that coordinate half has the +same fair-coin measure. The resulting Martin-Löf tests use the original +description strings, without a compiler or an increase in description length. +-/ + +@[expose] public section + +namespace Klr.ParityDescription + +open MeasureTheory AffineCode SparseSearch +open scoped ENNReal + +/-- One of the two coordinate halves of a binary sequence. -/ +def half (b : Fin 2) (X : Cantor) : Cantor := fun n => X (2 * n + b.val) + +/-- Insert a sequence in the indicated parity and put zeroes elsewhere. -/ +def fill (b : Fin 2) (Y : Cantor) : Cantor := + fun k => if k % 2 = b.val then Y (k / 2) else false + +/-- Retain one parity of a sequence and put zeroes elsewhere. -/ +def mask (b : Fin 2) (X : Cantor) : Cantor := + fun k => if k % 2 = b.val then X k else false + +theorem fill_half (b : Fin 2) (X : Cantor) : fill b (half b X) = mask b X := by + funext k + simp only [fill, half, mask] + split_ifs with hk + · congr 1 + omega + · rfl + +theorem half_fill (b : Fin 2) (X : Cantor) : half b (fill b X) = X := by + funext n + have hb := b.isLt + have hm : (2 * n + b.val) % 2 = b.val := by omega + have hd : (2 * n + b.val) / 2 = n := by omega + simp [half, fill, hm, hd] + +theorem measurable_half (b : Fin 2) : Measurable (half b) := by + unfold half + fun_prop + +theorem measurable_fill (b : Fin 2) : Measurable (fill b) := by + apply Measurable.of_eval + intro k + by_cases hk : k % 2 = b.val <;> simp only [fill, hk, ite_true, ite_false] <;> fun_prop + +/-- Injective coordinate selection preserves the fair product law. -/ +theorem fairCoin_map_half (b : Fin 2) : fairCoin.map (half b) = fairCoin := by + unfold fairCoin half + exact Measure.map_infinitePi_infinitePi_of_inj (by + intro i j hij + change 2 * i + b.val = 2 * j + b.val at hij + omega) + +/-- The finite version of `mask`. -/ +def maskWord (b : Fin 2) (s : List Bool) : List Bool := + ScanRule.inputPrefix (mask b (fun k => s.getD k false)) s.length + +/-- Interleave a finite word with zeroes in the other parity. -/ +def expandWord (b : Fin 2) (s : List Bool) : List Bool := + ScanRule.inputPrefix (fill b (fun k => s.getD k false)) (2 * s.length) + +@[simp] theorem length_maskWord (b : Fin 2) (s : List Bool) : + (maskWord b s).length = s.length := by simp [maskWord] + +@[simp] theorem length_expandWord (b : Fin 2) (s : List Bool) : + (expandWord b s).length = 2 * s.length := by simp [expandWord] + +theorem computable_maskWord (b : Fin 2) : Computable (maskWord b) := by + have hc : PrimrecPred (fun p : List Bool × ℕ => p.2 % 2 = b.val) := + Primrec.eq.comp (Primrec.nat_mod.comp Primrec.snd (Primrec.const 2)) + (Primrec.const b.val) + have hg : Primrec (fun p : List Bool × ℕ => + if p.2 % 2 = b.val then p.1.getD p.2 false else false) := + Primrec.ite hc ((Primrec.list_getD false).comp Primrec.fst Primrec.snd) + (Primrec.const false) + exact (Primrec.list_map (Primrec.list_range.comp Primrec.list_length) hg.to₂).to_comp + +theorem computable_expandWord (b : Fin 2) : Computable (expandWord b) := by + have hc : PrimrecPred (fun p : List Bool × ℕ => p.2 % 2 = b.val) := + Primrec.eq.comp (Primrec.nat_mod.comp Primrec.snd (Primrec.const 2)) + (Primrec.const b.val) + have hg : Primrec (fun p : List Bool × ℕ => + if p.2 % 2 = b.val then p.1.getD (p.2 / 2) false else false) := + Primrec.ite hc ((Primrec.list_getD false).comp Primrec.fst + (Primrec.nat_div.comp Primrec.snd (Primrec.const 2))) (Primrec.const false) + exact (Primrec.list_map + (Primrec.list_range.comp (Primrec.nat_mul.comp (Primrec.const 2) Primrec.list_length)) + hg.to₂).to_comp + +private theorem inputPrefix_congr (X Y : Cantor) (n : ℕ) + (h : ∀ k < n, X k = Y k) : ScanRule.inputPrefix X n = ScanRule.inputPrefix Y n := by + unfold ScanRule.inputPrefix + apply List.map_congr_left + intro k hk + exact h k (List.mem_range.mp hk) + +theorem maskWord_inputPrefix (b : Fin 2) (X : Cantor) (n : ℕ) : + maskWord b (ScanRule.inputPrefix X n) = ScanRule.inputPrefix (mask b X) n := by + unfold maskWord + rw [ScanRule.length_inputPrefix] + apply inputPrefix_congr + intro k hk + simp only [mask] + split_ifs + · exact ScanRule.getD_inputPrefix X hk + · rfl + +theorem expandWord_inputPrefix (b : Fin 2) (X : Cantor) (n : ℕ) : + expandWord b (ScanRule.inputPrefix X n) = ScanRule.inputPrefix (fill b X) (2 * n) := by + unfold expandWord + rw [ScanRule.length_inputPrefix] + apply inputPrefix_congr + intro k hk + have hd : k / 2 < n := by omega + simp only [fill] + split_ifs + · exact ScanRule.getD_inputPrefix X hd + · rfl + +theorem fill_mem_cylinder_expandWord (b : Fin 2) {X : Cantor} {s : List Bool} + (hX : X ∈ cylinder s) : fill b X ∈ cylinder (expandWord b s) := by + intro k hk + have hk' : k < 2 * s.length := by simpa using hk + change fill b X k = + (ScanRule.inputPrefix (fill b (fun j => s.getD j false)) (2 * s.length)).getD k false + rw [ScanRule.getD_inputPrefix _ hk'] + simp only [fill] + split_ifs + · exact (mem_cylinder.mp hX) (k / 2) (by omega) + · rfl + +/-- A finite exhaustive check that deleting the opposite parity preserves acceptance. -/ +def supported (b : Fin 2) (c : Data) : Bool := + (words (width c)).all (fun s => decide (accepts c s = accepts c (maskWord b s))) + +theorem supported_eq_true (b : Fin 2) (c : Data) : + supported b c = true ↔ + ∀ s : List Bool, s.length = width c → accepts c s = accepts c (maskWord b s) := by + simp [supported, List.all_eq_true, mem_words_iff] + +theorem computable_supported (b : Fin 2) : Computable (supported b) := by + have ht : Computable (fun p : Data × List Bool => + decide (accepts p.1 p.2 = accepts p.1 (maskWord b p.2))) := + Primrec.eq.decide.to_comp.comp computable_accepts + (computable_accepts.comp Computable.fst ((computable_maskWord b).comp Computable.snd)) + exact computable_list_all (computable_words.comp computable_width) ht.to₂ + +/-- The finite filter implies the corresponding invariance of the infinite event. -/ +theorem event_mask_iff (b : Fin 2) {c : Data} (hs : supported b c = true) (X : Cantor) : + X ∈ event c ↔ mask b X ∈ event c := by + have h := (supported_eq_true b c).mp hs (ScanRule.inputPrefix X (width c)) + (ScanRule.length_inputPrefix X (width c)) + rw [maskWord_inputPrefix] at h + rw [← StageFiniteProbability.accepts_code_inputPrefix c (width c) le_rfl X, + ← StageFiniteProbability.accepts_code_inputPrefix c (width c) le_rfl (mask b X)] + exact iff_of_eq (congrArg (fun q : Bool => q = true) h) + +/-- Event equality suffices for the filter; no special output matrix representation is needed. -/ +theorem supported_of_event_eq (b : Fin 2) {c : Data} {B : AffineBlock} + (he : event c = B.event) (hB : ∀ k ∈ B.support, k % 2 = b.val) : + supported b c = true := by + apply (supported_eq_true b c).mpr + intro s hs + let X : Cantor := fun k => s.getD k false + have hp : ScanRule.inputPrefix X (width c) = s := by + rw [← hs] + exact StageCodeSearch.inputPrefix_getD s + rw [← hp, maskWord_inputPrefix] + apply Bool.eq_iff_iff.mpr + rw [StageFiniteProbability.accepts_code_inputPrefix c (width c) le_rfl X, + StageFiniteProbability.accepts_code_inputPrefix c (width c) le_rfl (mask b X), he] + apply iff_of_eq + apply B.dependsOn_event + intro k hk + simp [mask, hB k hk] + +/-- The event on a coordinate half obtained by zero filling the other coordinates. -/ +def halfEvent (b : Fin 2) (c : Data) : Set Cantor := fill b ⁻¹' event c + +theorem measurableSet_halfEvent (b : Fin 2) (c : Data) : MeasurableSet (halfEvent b c) := + (measurableSet_event c).preimage (measurable_fill b) + +theorem event_eq_preimage_halfEvent (b : Fin 2) {c : Data} (hs : supported b c = true) : + event c = half b ⁻¹' halfEvent b c := by + ext X + change X ∈ event c ↔ fill b (half b X) ∈ event c + rw [fill_half] + exact event_mask_iff b hs X + +/-- Deleting irrelevant coordinates preserves the exact probability, not just an upper bound. -/ +theorem fairCoin_halfEvent (b : Fin 2) {c : Data} (hs : supported b c = true) : + fairCoin (halfEvent b c) = fairCoin (event c) := by + rw [event_eq_preimage_halfEvent b hs, + ← Measure.map_apply (measurable_half b) (measurableSet_halfEvent b c), fairCoin_map_half] + +theorem cylinderUnion_expanded_accepts (b : Fin 2) (c : Data) : + cylinderUnion (fun s => accepts c (expandWord b s) = true) = halfEvent b c := by + ext X + constructor + · rintro ⟨s, hs, hX⟩ + exact cylinder_subset_event hs (fill_mem_cylinder_expandWord b hX) + · intro hX + refine ⟨ScanRule.inputPrefix X (width c), ?_, ScanRule.mem_cylinder_inputPrefix _ _⟩ + change accepts c (expandWord b (ScanRule.inputPrefix X (width c))) = true + rw [expandWord_inputPrefix] + exact (StageFiniteProbability.accepts_code_inputPrefix c (2 * width c) (by omega) + (fill b X)).mpr hX + +/-- The finite postprocessing check keeps the original program and its original rank budget. -/ +def check (b : Fin 2) (a : ℕ × List Bool × List Bool) (c : Data) : Bool := + supported b c && AffineDescription.check (a.1, a.2.1, expandWord b a.2.2) c + +theorem check_eq_true (b : Fin 2) (a : ℕ × List Bool × List Bool) (c : Data) : + check b a c = true ↔ supported b c = true ∧ valid c = true ∧ + 2 * a.2.1.length + a.1 + 1 ≤ rank c ∧ accepts c (expandWord b a.2.2) = true := by + simp [check, AffineDescription.check_eq_true] + +theorem computable_check (b : Fin 2) : Computable₂ (check b) := by + have ht : Computable (fun a : ℕ × List Bool × List Bool => + (a.1, a.2.1, expandWord b a.2.2)) := + Computable.fst.pair ((Computable.fst.comp Computable.snd).pair + ((computable_expandWord b).comp (Computable.snd.comp Computable.snd))) + exact Primrec.and.to_comp.comp ((computable_supported b).comp Computable.snd) + (AffineDescription.computable_check.comp (ht.comp Computable.fst) Computable.snd) + +/-- The cylinder enumeration for the test on parity `b`. -/ +def W (b : Fin 2) (a : ℕ × List Bool × List Bool) : Prop := + ∃ c : Data, c ∈ AffineDescription.run a.2.1 ∧ supported b c = true ∧ valid c = true ∧ + 2 * a.2.1.length + a.1 + 1 ≤ rank c ∧ accepts c (expandWord b a.2.2) = true + +theorem rePred_W (b : Fin 2) : REPred (W b) := by + let accept (a : ℕ × List Bool × List Bool) : Part Unit := + (AffineDescription.run a.2.1).bind fun c => + if check b a c then Part.some () else Part.none + have hp : Computable (fun a : ℕ × List Bool × List Bool => a.2.1) := + Computable.fst.comp Computable.snd + have hfilter : Partrec (fun p : (ℕ × List Bool × List Bool) × Data => + if check b p.1 p.2 then Part.some () else Part.none) := by + have ht : Partrec (fun _ : (ℕ × List Bool × List Bool) × Data => Part.some ()) := + (Computable.const ()).partrec + have hf : Partrec (fun _ : (ℕ × List Bool × List Bool) × Data => + (Part.none : Part Unit)) := Partrec.none + have hc := Partrec.cond (c := fun p : (ℕ × List Bool × List Bool) × Data => + check b p.1 p.2) (computable_check b) ht hf + exact hc.of_eq fun p => by cases check b p.1 p.2 <;> rfl + have he : Partrec accept := (AffineDescription.partrec_run.comp hp).bind + (g := fun a c => if check b a c then Part.some () else Part.none) hfilter.to₂ + apply he.dom_re.of_eq + intro a + simp only [accept, Part.dom_iff_mem, Part.mem_bind_iff] + constructor + · rintro ⟨u, c, hc, hu⟩ + have hcheck : check b a c = true := by + cases hh : check b a c <;> simp [hh] at hu ⊢ + exact ⟨c, hc, (check_eq_true b a c).mp hcheck⟩ + · rintro ⟨c, hc, hs, hv, hr, ha⟩ + refine ⟨(), c, hc, ?_⟩ + simp [(check_eq_true b a c).mpr ⟨hs, hv, hr, ha⟩] + +theorem cylinderUnion_W_eq (b : Fin 2) {n : ℕ} {p : List Bool} {c : Data} + (hc : c ∈ AffineDescription.run p) (hs : supported b c = true) (hv : valid c = true) + (hr : 2 * p.length + n + 1 ≤ rank c) : + cylinderUnion (fun s => W b (n, p, s)) = halfEvent b c := by + rw [← cylinderUnion_expanded_accepts b c] + congr 1 + funext s + apply propext + constructor + · rintro ⟨d, hd, _, _, _, ha⟩ + have hdc : d = c := Part.mem_unique hd hc + simpa only [hdc] using ha + · intro ha + exact ⟨c, hc, hs, hv, hr, ha⟩ + +/-- Each original program retains precisely its original description-measure budget. -/ +theorem per_program_bound (b : Fin 2) (n : ℕ) (p : List Bool) : + fairCoin (cylinderUnion (fun s => W b (n, p, s))) ≤ + (1 / 2 : ℝ≥0∞) ^ (2 * p.length + n + 1) := by + classical + by_cases h : ∃ c : Data, c ∈ AffineDescription.run p ∧ supported b c = true ∧ + valid c = true ∧ 2 * p.length + n + 1 ≤ rank c + · obtain ⟨c, hc, hs, hv, hr⟩ := h + rw [cylinderUnion_W_eq b hc hs hv hr, fairCoin_halfEvent b hs, fairCoin_event c hv] + exact pow_le_pow_of_le_one (by positivity) (by norm_num) hr + · have hempty : cylinderUnion (fun s => W b (n, p, s)) = ∅ := by + apply Set.eq_empty_iff_forall_notMem.mpr + rintro X ⟨s, ⟨c, hc, hs, hv, hr, _⟩, _⟩ + exact h ⟨c, hc, hs, hv, hr⟩ + rw [hempty, measure_empty] + positivity + +/-- Both parity-indexed families are actual Martin-Löf tests. -/ +theorem exists_martinLofTest (b : Fin 2) : + ∃ T : MartinLofTest, ∀ n, T.level n = descriptionLevel (W b) n := + exists_martinLofTest_of_description_family (rePred_W b) (per_program_bound b) + +theorem not_martinLofRandom_half_of_descriptions (b : Fin 2) (X : Cantor) + (hX : ∀ n, ∃ (p : List Bool) (c : Data), c ∈ AffineDescription.run p ∧ + supported b c = true ∧ valid c = true ∧ + 2 * p.length + n + 1 ≤ rank c ∧ X ∈ event c) : + ¬MartinLofRandom (half b X) := by + apply not_martinLofRandom_of_descriptions (rePred_W b) (per_program_bound b) + intro n + obtain ⟨p, c, hc, hs, hv, hr, hmem⟩ := hX n + refine ⟨p, ?_⟩ + rw [cylinderUnion_W_eq b hc hs hv hr] + change fill b (half b X) ∈ event c + rw [fill_half] + exact (event_mask_iff b hs X).mp hmem + +/-- Alternating parity-supported blocks with the original stage descriptions +make either coordinate half fail its own effective test. -/ +theorem not_martinLofRandom_half_of_blocks (B : ℕ → AffineBlock) + (hparity : ∀ j, ∀ k ∈ (B j).support, k % 2 = j % 2) + (hprogram : ∀ j, ∃ (p : List Bool) (c : Data), c ∈ AffineDescription.run p ∧ + valid c = true ∧ 2 * p.length + j + 1 ≤ rank c ∧ event c = (B j).event) + (X : Cantor) (hX : ∀ j, X ∈ (B j).event) (b : Fin 2) : + ¬MartinLofRandom (half b X) := by + apply not_martinLofRandom_half_of_descriptions b X + intro n + obtain ⟨p, c, hc, hv, hr, he⟩ := hprogram (2 * n + b.val) + have hb := b.isLt + refine ⟨p, c, hc, supported_of_event_eq b he ?_, hv, ?_, ?_⟩ + · intro k hk + have hp := hparity (2 * n + b.val) k hk + omega + · omega + · rw [he] + exact hX _ + +theorem both_halves_not_martinLofRandom_of_blocks (B : ℕ → AffineBlock) + (hparity : ∀ j, ∀ k ∈ (B j).support, k % 2 = j % 2) + (hprogram : ∀ j, ∃ (p : List Bool) (c : Data), c ∈ AffineDescription.run p ∧ + valid c = true ∧ 2 * p.length + j + 1 ≤ rank c ∧ event c = (B j).event) + (X : Cantor) (hX : ∀ j, X ∈ (B j).event) : + ¬MartinLofRandom (half 0 X) ∧ ¬MartinLofRandom (half 1 X) := + ⟨not_martinLofRandom_half_of_blocks B hparity hprogram X hX 0, + not_martinLofRandom_half_of_blocks B hparity hprogram X hX 1⟩ + +end Klr.ParityDescription diff --git a/LeanPool/KLRandomness/ParityPools.lean b/LeanPool/KLRandomness/ParityPools.lean new file mode 100644 index 0000000000..9a8d753da6 --- /dev/null +++ b/LeanPool/KLRandomness/ParityPools.lean @@ -0,0 +1,268 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.PoolConstruction +public import LeanPool.KLRandomness.StageReconstruction +public import LeanPool.KLRandomness.PairRespecting +import Mathlib.Tactic.Linarith +import Mathlib.Tactic.NormNum + +/-! +# Common Borel partitions for even and odd pools + +Two auxiliary scans reading only even positions force the existing weighted +pool construction to select even pools. A pair-respecting scan eventually +reads an even position precisely when it reads its odd partner, so shifting +the completed pool preserves both missed-position estimates. The auxiliary +scans are used only in the pool argument. +-/ + +@[expose] public section + +namespace Klr.ParityPools + +open Filter MeasureTheory PoolConstruction +open scoped Topology BigOperators + +/-- A computable scan which reads all even positions in order. -/ +def evenScan : ScanRule where + query v := 2 * v.length + computable_query := Primrec.nat_mul.to_comp.comp (Computable.const 2) Computable.list_length + fresh := by + intro v n hn + simp only [List.length_take, Nat.min_eq_left hn.le] + omega + +@[simp] theorem reads_evenScan (a : ℕ) (Z : Cantor) : + PoolQuery.Reads evenScan a Z ↔ a % 2 = 0 := by + change (∃ t, 2 * (ScanRule.inputPrefix Z t).length = a) ↔ _ + simp only [ScanRule.inputPrefix, List.length_map, List.length_range] + constructor + · rintro ⟨t, rfl⟩ + omega + · intro ha + exact ⟨a / 2, by omega⟩ + +theorem queryProbability_evenScan (a : ℕ) : + Pool.queryProbability evenScan a = if a % 2 = 0 then 1 else 0 := by + rw [Pool.queryProbability_eq_measureReal] + by_cases ha : a % 2 = 0 <;> simp [ha] + +/-- The two auxiliary weights sum to three quarters. -/ +def augmented (π : ℕ → ScanRule) : ℕ → ScanRule + | 0 => evenScan + | 1 => evenScan + | i + 2 => π i + +theorem weighted_even_lower (π : ℕ → ScanRule) {a : ℕ} (ha : a % 2 = 0) : + (3 / 4 : ℝ) ≤ Pool.weightedQueryProbability (augmented π) a := by + have h := (Pool.weighted_query_truncation (augmented π) a 2).1 + norm_num [Finset.sum_range_succ, augmented, Pool.weight, queryProbability_evenScan, ha] at h + linarith + +theorem weighted_odd_upper (π : ℕ → ScanRule) {a : ℕ} (ha : a % 2 ≠ 0) : + Pool.weightedQueryProbability (augmented π) a ≤ (1 / 4 : ℝ) := by + have h := (Pool.weighted_query_truncation (augmented π) a 2).2 + norm_num [Finset.sum_range_succ, augmented, Pool.weight, queryProbability_evenScan, ha] at h + exact h + +theorem limsup_gt_half (π : ℕ → ScanRule) : + (1 / 2 : ℝ) < Pool.weightedQueryLimsup (augmented π) := by + obtain ⟨z, hz⟩ := Pool.exists_weighted_query_upper_cutoff (augmented π) + (show (0 : ℝ) < 1 / 8 by norm_num) + have hu := hz (2 * z) (by omega) + have hl := weighted_even_lower π (a := 2 * z) (by omega) + linarith + +theorem eventually_even {π : ℕ → ScanRule} {a : ℕ → ℕ} + (Q : Pool.QueryPartition (augmented π) a) + (hp : Tendsto (Pool.weightedQueryProbability (augmented π) ∘ Q.position) atTop + (𝓝 (Pool.weightedQueryLimsup (augmented π)))) : + ∀ᶠ n : ℕ in atTop, Q.position n % 2 = 0 := by + have he := hp.eventually (lt_mem_nhds (limsup_gt_half π)) + filter_upwards [he] with n hn + by_contra hodd + have h := weighted_odd_upper π hodd + dsimp only [Function.comp_def] at hn + linarith + +/-- The first dummy scan has a full-measure high set. -/ +theorem high_zero_measure {π : ℕ → ScanRule} {a : ℕ → ℕ} + (Q : Pool.QueryPartition (augmented π) a) + (hp : Tendsto (Pool.weightedQueryProbability (augmented π) ∘ Q.position) atTop + (𝓝 (Pool.weightedQueryLimsup (augmented π)))) : + fairCoin.real (Q.high 0) = 1 := by + have hq : (fun n => Pool.queryProbability (augmented π 0) (Q.position n)) + =ᶠ[atTop] (fun _ => (1 : ℝ)) := by + filter_upwards [eventually_even Q hp] with n hn + simp [augmented, queryProbability_evenScan, hn] + have hi : (∫ Z, Q.limit 0 Z ∂fairCoin) = 1 := + tendsto_nhds_unique (Q.queryProbability_tendsto 0) + (tendsto_const_nhds.congr' hq.symm) + have hrep : Q.representative 0 =ᵐ[fairCoin] (fun _ => (1 : ℝ)) := by + apply (integral_eq_iff_of_ae_le + ((Pool.integrable_L2 (Q.limit 0)).congr (Q.representative_ae_eq 0).symm) + (integrable_const 1) + (Filter.Eventually.of_forall fun Z => (Q.representative_bounds 0 Z).2)).mp + rw [Q.integral_representative, hi] + simp + have hs : Q.high 0 =ᵐ[fairCoin] Set.univ := by + filter_upwards [hrep] with Z hZ + change (Q.representative 0 Z = 1) ↔ (Z ∈ Set.univ) + simp [hZ] + rw [measureReal_congr hs] + simp + +/-- Every sufficiently accurate good pool for the augmented family is even. -/ +theorem even_of_goodPool {π : ℕ → ScanRule} {H : ℕ → Set Cantor} + (hH : fairCoin.real (H 0) = 1) {ℓ z M : ℕ} {η : ℝ} {τ : ℚ} {G : List ℕ} + (hη : η < 1) (hG : GoodPool (augmented π) H (ℓ + 2) η z τ M G) : + ∀ b ∈ G, b % 2 = 0 := by + intro b hb + by_contra hodd + have hh := (hG.2.2.2 0 (by omega)).1 + have he : {Z | Z ∈ H 0 ∧ ∃ a ∈ G, ¬ PoolQuery.Reads (augmented π 0) a Z} = H 0 := by + ext Z + constructor + · exact And.left + · intro hZ + exact ⟨hZ, b, hb, by simpa [augmented] using hodd⟩ + rw [he, hH] at hh + linarith + +theorem strip_goodPool {π : ℕ → ScanRule} {H : ℕ → Set Cantor} + {ℓ z M : ℕ} {η ε : ℝ} {τ : ℚ} {G : List ℕ} (hη : η ≤ ε) + (hG : GoodPool (augmented π) H (ℓ + 2) η z τ M G) : + GoodPool π (fun i => H (i + 2)) ℓ ε z τ M G := by + refine ⟨hG.1, hG.2.1, hG.2.2.1, ?_⟩ + intro i hi + have h := hG.2.2.2 (i + 2) (by omega) + exact ⟨h.1.trans_le hη, h.2.trans_le hη⟩ + +/-- The existing fixed-advice search can already produce confined even pools. -/ +theorem exists_fixed_partitions_even_pools (π : ℕ → ScanRule) : + ∃ H : ℕ → Set Cantor, (∀ i, MeasurableSet (H i)) ∧ + ∀ (ℓ : ℕ) (η : ℝ), 0 < η → ∀ z : ℕ, + ∃ τ : ℚ, 0 < τ ∧ τ < 1 / 4 ∧ + ∃ e : Nat.Partrec.Code, ∀ᶠ M : ℕ in atTop, + ∃ G : List ℕ, PoolAdvice.encodePool G ∈ e.eval M ∧ + GoodPool π H ℓ η z τ M G ∧ ∀ b ∈ G, b % 2 = 0 := by + obtain ⟨a, Q, ha, hp, _⟩ := Pool.exists_weighted_queryPartition (augmented π) + refine ⟨fun i => Q.high (i + 2), fun i => Q.measurableSet_high (i + 2), ?_⟩ + intro ℓ η hη z + let ε := min η (1 / 2 : ℝ) + have hε : 0 < ε := lt_min hη (by norm_num) + obtain ⟨P⟩ := PoolAdvice.exists_fixedParameters Q (ℓ + 2) hε z + obtain ⟨e, he⟩ := FixedParameters.exists_eventual_goodPool_program P ha hp + refine ⟨P.margin, P.margin_pos, P.margin_lt_quarter, e, ?_⟩ + filter_upwards [he] with M hM + obtain ⟨G, hcode, hG⟩ := hM + exact ⟨G, hcode, strip_goodPool (min_le_left _ _) hG, + even_of_goodPool (high_zero_measure Q hp) + ((min_le_right _ _).trans_lt (by norm_num)) hG⟩ + +theorem reads_add_parity {π : ScanRule} (hπ : π.PairRespecting) + {a c : ℕ} (ha : a % 2 = 0) (hc : c < 2) (Z : Cantor) : + PoolQuery.Reads π (a + c) Z ↔ PoolQuery.Reads π a Z := by + have hc' : c = 0 ∨ c = 1 := by omega + rcases hc' with rfl | rfl + · simp + · have he : a = 2 * (a / 2) := by omega + rw [he] + exact (hπ.reads_even_iff_reads_odd Z (a / 2)).symm + +theorem missedCount_map_add {π : ScanRule} (hπ : π.PairRespecting) + (G : List ℕ) (hG : ∀ a ∈ G, a % 2 = 0) (c : ℕ) (hc : c < 2) (Z : Cantor) : + PoolQuery.missedCount π (G.map (· + c)).toFinset Z = + PoolQuery.missedCount π G.toFinset Z := by + classical + have hm : (G.map (· + c)).toFinset = G.toFinset.image (· + c) := by + ext a + simp + simp only [PoolQuery.missedCount, hm, Finset.filter_image] + have he : G.toFinset.filter (fun a => ¬ PoolQuery.Reads π (a + c) Z) = + G.toFinset.filter (fun a => ¬ PoolQuery.Reads π a Z) := by + apply Finset.filter_congr + intro a ha + exact not_congr (reads_add_parity hπ (hG a (List.mem_toFinset.mp ha)) hc Z) + rw [he, Finset.card_image_of_injective _ (fun _ _ h => Nat.add_right_cancel h)] + +/-- Translating even pools by either parity preserves the completed infinite +miss events. No equality of finite-horizon hit events is asserted. -/ +theorem goodPool_map_add {π : ℕ → ScanRule} (hπ : ∀ i, (π i).PairRespecting) + {H : ℕ → Set Cantor} {ℓ z M : ℕ} {η : ℝ} {τ : ℚ} {G : List ℕ} + (hG : GoodPool π H ℓ η z τ M G) (heven : ∀ a ∈ G, a % 2 = 0) + (c : ℕ) (hc : c < 2) : + GoodPool π H ℓ η z τ M (G.map (· + c)) := by + refine ⟨by simpa using hG.1, + hG.2.1.map (fun _ _ h => Nat.add_right_cancel h), ?_, ?_⟩ + · intro a ha + obtain ⟨b, hb, rfl⟩ := List.mem_map.mp ha + exact (hG.2.2.1 b hb).trans (Nat.le_add_right _ _) + · intro i hi + have hreads : ∀ Z, (∃ a ∈ G.map (· + c), ¬ PoolQuery.Reads (π i) a Z) ↔ + ∃ a ∈ G, ¬ PoolQuery.Reads (π i) a Z := by + intro Z + constructor + · rintro ⟨a, ha, hm⟩ + obtain ⟨b, hb, rfl⟩ := List.mem_map.mp ha + exact ⟨b, hb, (not_congr (reads_add_parity (hπ i) (heven b hb) hc Z)).mp hm⟩ + · rintro ⟨a, ha, hm⟩ + exact ⟨a + c, List.mem_map.mpr ⟨a, ha, rfl⟩, + (not_congr (reads_add_parity (hπ i) (heven a ha) hc Z)).mpr hm⟩ + simpa only [hreads, missedCount_map_add (hπ i) G heven c hc] using hG.2.2.2 i hi + +theorem exists_shifted_program (e : Nat.Partrec.Code) (c : ℕ) : + ∃ e' : Nat.Partrec.Code, ∀ M G, + PoolAdvice.encodePool G ∈ e.eval M → + PoolAdvice.encodePool (G.map (· + c)) ∈ e'.eval M := by + have hm : Computable (fun G : List ℕ => G.map (· + c)) := + (Primrec.list_map Primrec.id + (Primrec.nat_add.comp Primrec.snd (Primrec.const c)).to₂).to_comp + let f : ℕ → Part (List ℕ) := fun M => + (e.eval M).map (fun k => (StageReconstruction.decodePool k).map (· + c)) + have hf : Partrec f := + (Nat.Partrec.Code.eval_part.comp (Computable.const e) Computable.id).map + ((hm.comp StageReconstruction.computable_decodePool).comp Computable.snd) + obtain ⟨e', he'⟩ := Nat.Partrec.Code.exists_code.mp hf + refine ⟨e', ?_⟩ + intro M G hG + rw [he'] + simp only [Encodable.decode_nat, Part.coe_some, Part.bind_some] + change PoolAdvice.encodePool (G.map (· + c)) ∈ (f M).map PoolAdvice.encodePool + apply Part.mem_map + simpa only [f, StageReconstruction.decodePool_encodePool] using + Part.mem_map (fun k => (StageReconstruction.decodePool k).map (· + c)) hG + +/-- One fixed family of Borel partitions supplies both parity classes, with +the parity selected before choosing the fixed pool program. -/ +theorem exists_fixed_partitions_parity_pools (π : ℕ → ScanRule) + (hπ : ∀ i, (π i).PairRespecting) : + ∃ H : ℕ → Set Cantor, (∀ i, MeasurableSet (H i)) ∧ + ∀ (ℓ : ℕ) (η : ℝ), 0 < η → ∀ z c : ℕ, c < 2 → + ∃ τ : ℚ, 0 < τ ∧ τ < 1 / 4 ∧ + ∃ e : Nat.Partrec.Code, ∀ᶠ M : ℕ in atTop, + ∃ G : List ℕ, PoolAdvice.encodePool G ∈ e.eval M ∧ + GoodPool π H ℓ η z τ M G ∧ ∀ b ∈ G, b % 2 = c := by + obtain ⟨H, hH, hpool⟩ := exists_fixed_partitions_even_pools π + refine ⟨H, hH, ?_⟩ + intro ℓ η hη z c hc + obtain ⟨τ, hτ, hτlt, e, he⟩ := hpool ℓ η hη z + obtain ⟨e', he'⟩ := exists_shifted_program e c + refine ⟨τ, hτ, hτlt, e', ?_⟩ + filter_upwards [he] with M hM + obtain ⟨G, hcode, hG, hGeven⟩ := hM + refine ⟨G.map (· + c), he' M G hcode, goodPool_map_add hπ hG hGeven c hc, ?_⟩ + intro b hb + obtain ⟨a, ha, rfl⟩ := List.mem_map.mp hb + have h := hGeven a ha + omega + +end Klr.ParityPools diff --git a/LeanPool/KLRandomness/PartialBetting.lean b/LeanPool/KLRandomness/PartialBetting.lean new file mode 100644 index 0000000000..05c6d96716 --- /dev/null +++ b/LeanPool/KLRandomness/PartialBetting.lean @@ -0,0 +1,491 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.Betting +public import Mathlib.Computability.PartrecCode +public import Mathlib.Computability.Primrec.List +public import Mathlib.Data.Nat.Bits + +/-! +# A total fresh-query scheduler for partial KL programs + +A partial program receives the previously completed answers and returns a query +position and a rational wager. The scheduler spends one bounded-computation +stage per outward query. While waiting, it reads a fresh position in the parity +on which it never wagers. Previously read answers are cached: if the simulated +program subsequently requests one, that answer is replayed without a second +query. Each outward query is fresh, including when the program diverges. + +The even/odd splitting argument is Merkle's totalization construction, described +in Bienvenu's thesis, Remark 1.7.7. The cached-answer replay is made explicit +here because a nonmonotonic scan is not allowed to read a position twice. +-/ + +@[expose] public section + +namespace Klr.PartialBetting + +/-- A program output: position, signed numerator, and natural denominator. +The wager is clipped to `[-1,1]` so every program code defines legal bets. -/ +abbrev Action := ℕ × (ℤ × ℕ) + +/-- A finite assignment, recorded in the order in which its answers were read. -/ +abbrev Assignment := List (ℕ × Bool) + +/-- Completed simulated queries, actual observed queries, and a computation +budget for the next simulated action. The actual observations are cached in +reverse order; the simulated assignment is in chronological order. -/ +abbrev State := Assignment × (Assignment × ℕ) + +/-- The scheduler state before any queries or program evaluation. -/ +def initial : State := ([], [], 0) + +/-- The ordinary partial recursive action described by a program code. -/ +def partialAction (c : Nat.Partrec.Code) (v : List Bool) : Part Action := + (c.eval (Encodable.encode v)).map (Denumerable.ofNat Action) + +theorem exists_partialAction (f : List Bool → Part Action) (hf : Partrec f) : + ∃ c : Nat.Partrec.Code, ∀ v, partialAction c v = f v := by + obtain ⟨c, hc⟩ := Nat.Partrec.Code.exists_code.mp hf + refine ⟨c, fun v => ?_⟩ + have hdecode : Denumerable.ofNat Action ∘ Encodable.encode = @id Action := by + funext a + exact Denumerable.ofNat_encode a + simp only [partialAction, hc, Encodable.encodek, Part.coe_some, Part.bind_some, + Part.map_map, hdecode] + exact Part.map_id' (fun _ => rfl) _ + +/-- Run the source program for a bounded time on the cached answer transcript. -/ +def approximate (c : Nat.Partrec.Code) (v : Assignment) (t : ℕ) : Option Action := + (c.evaln t (Encodable.encode (v.map Prod.snd))).map (Denumerable.ofNat Action) + +theorem approximate_complete (c : Nat.Partrec.Code) (v : Assignment) (a : Action) : + a ∈ partialAction c (v.map Prod.snd) ↔ ∃ t, approximate c v t = some a := by + rw [partialAction, Part.mem_map_iff] + constructor + · rintro ⟨k, hk, rfl⟩ + obtain ⟨t, ht⟩ := Nat.Partrec.Code.evaln_complete.mp hk + exact ⟨t, Option.map_eq_some_iff.mpr ⟨k, ht, rfl⟩⟩ + · rintro ⟨t, ht⟩ + obtain ⟨k, hk, ha⟩ := Option.map_eq_some_iff.mp ht + exact ⟨k, Nat.Partrec.Code.evaln_sound hk, ha⟩ + +theorem approximate_mono (c : Nat.Partrec.Code) (v : Assignment) + {s t : ℕ} {a : Action} (hst : s ≤ t) (h : approximate c v s = some a) : + approximate c v t = some a := by + obtain ⟨k, hk, rfl⟩ := Option.map_eq_some_iff.mp h + exact Option.map_eq_some_iff.mpr + ⟨k, Nat.Partrec.Code.evaln_mono hst hk, rfl⟩ + +theorem approximate_unique (c : Nat.Partrec.Code) (v : Assignment) + {s t : ℕ} {a b : Action} (ha : approximate c v s = some a) + (hb : approximate c v t = some b) : a = b := by + have ha' := approximate_mono c v (Nat.le_max_left s t) ha + have hb' := approximate_mono c v (Nat.le_max_right s t) hb + exact Option.some.inj (ha'.symm.trans hb') + +/-- Look up an already observed answer. -/ +def lookup (q : ℕ) : Assignment → Option Bool + | [] => none + | (p, b) :: xs => if q = p then some b else lookup q xs + +@[simp] theorem lookup_nil (q : ℕ) : lookup q [] = none := rfl + +@[simp] theorem lookup_cons (q p : ℕ) (b : Bool) (xs : Assignment) : + lookup q ((p, b) :: xs) = if q = p then some b else lookup q xs := rfl + +theorem lookup_eq_none_iff (q : ℕ) (xs : Assignment) : + lookup q xs = none ↔ ∀ b, (q, b) ∉ xs := by + induction xs with + | nil => simp + | cons p xs ih => + rcases p with ⟨p, b⟩ + by_cases h : q = p + · subst p + constructor + · intro h + simp at h + · intro h + exact False.elim (h b (by simp)) + · simp [h, ih] + +theorem mem_of_lookup_eq_some {q : ℕ} {b : Bool} {xs : Assignment} + (h : lookup q xs = some b) : (q, b) ∈ xs := by + induction xs with + | nil => simp at h + | cons p xs ih => + rcases p with ⟨p, d⟩ + by_cases hp : q = p + · simp [hp] at h + subst p + subst d + simp + · simp only [lookup_cons, hp, ite_false] at h + exact List.mem_cons_of_mem _ (ih h) + +/-- A convenient strict upper bound on every coordinate in an assignment. -/ +def bound : Assignment → ℕ + | [] => 0 + | (q, _) :: xs => q + bound xs + 1 + +theorem lt_bound_of_mem {q : ℕ} {b : Bool} {xs : Assignment} + (h : (q, b) ∈ xs) : q < bound xs := by + induction xs with + | nil => simp at h + | cons p xs ih => + rcases p with ⟨p, d⟩ + simp only [List.mem_cons, Prod.mk.injEq] at h + rcases h with ⟨rfl, rfl⟩ | h + · simp [bound] + · have := ih h + simp only [bound] + omega + +/-- `side = false` means wagering only at even coordinates. -/ +def filler (side : Bool) (xs : Assignment) : ℕ := + 2 * bound xs + if side then 0 else 1 + +@[simp] theorem bodd_filler (side : Bool) (xs : Assignment) : + (filler side xs).bodd = !side := by + cases side <;> simp [filler] + +theorem filler_not_mem (side : Bool) (xs : Assignment) (b : Bool) : + (filler side xs, b) ∉ xs := by + intro h + have := lt_bound_of_mem h + cases side <;> simp only [filler, Bool.false_eq_true, ite_false, ite_true] at this <;> + omega + +/-- The next genuine query. A ready action is queried only if its answer is +not already cached; all other cases consume a fresh inactive coordinate. -/ +def query (c : Nat.Partrec.Code) (side : Bool) (s : State) : ℕ := + match approximate c s.1 s.2.2 with + | none => filler side s.2.1 + | some a => match lookup a.1 s.2.1 with + | none => a.1 + | some _ => filler side s.2.1 + +/-- Consume one outward answer and perform at most one simulated action. -/ +def advance (c : Nat.Partrec.Code) (side : Bool) (s : State) (b : Bool) : State := + let observed := (query c side s, b) :: s.2.1 + match approximate c s.1 s.2.2 with + | none => (s.1, observed, s.2.2 + 1) + | some a => (s.1 ++ [(a.1, (lookup a.1 s.2.1).getD b)], observed, 0) + +/-- The scheduler state after processing a finite transcript of actual answers. -/ +def state (c : Nat.Partrec.Code) (side : Bool) (v : List Bool) : State := + v.foldl (advance c side) initial + +@[simp] theorem state_nil (c : Nat.Partrec.Code) (side : Bool) : + state c side [] = initial := rfl + +@[simp] theorem state_snoc (c : Nat.Partrec.Code) (side : Bool) + (v : List Bool) (b : Bool) : + state c side (v ++ [b]) = advance c side (state c side v) b := by + simp [state, List.foldl_append] + +@[simp] theorem advance_observed (c : Nat.Partrec.Code) (side : Bool) + (s : State) (b : Bool) : + (advance c side s b).2.1 = (query c side s, b) :: s.2.1 := by + simp only [advance] + split <;> rfl + +theorem query_not_mem (c : Nat.Partrec.Code) (side : Bool) + (s : State) (b : Bool) : (query c side s, b) ∉ s.2.1 := by + unfold query + split + · exact filler_not_mem side _ b + · split + · exact (lookup_eq_none_iff _ _).mp ‹_› b + · exact filler_not_mem side _ b + +theorem previous_query_mem (c : Nat.Partrec.Code) (side : Bool) + (v : List Bool) (n : ℕ) (hn : n < v.length) : + ∃ b, (query c side (state c side (v.take n)), b) ∈ (state c side v).2.1 := by + induction v using List.reverseRecOn with + | nil => simp at hn + | append_singleton v b ih => + simp only [List.length_append, List.length_singleton] at hn + rw [state_snoc, advance_observed] + rcases lt_or_eq_of_le (Nat.le_of_lt_succ hn) with h | rfl + · obtain ⟨d, hd⟩ := ih h + exact ⟨d, List.mem_cons_of_mem _ (by simpa [List.take_append_of_le_length h.le] using hd)⟩ + · exact ⟨b, by simp⟩ + +theorem primrec_approximate (c : Nat.Partrec.Code) : Primrec₂ (approximate c) := by + have hv : Primrec (fun p : Assignment × ℕ => p.1.map Prod.snd) := + Primrec.list_map Primrec.fst (Primrec.snd.comp Primrec.snd).to₂ + exact (Primrec.option_map + (Nat.Partrec.Code.primrec_evaln.comp + ((Primrec.snd.pair (Primrec.const c)).pair (Primrec.encode.comp hv))) + ((Primrec.ofNat Action).comp Primrec.snd).to₂).to₂ + +theorem primrec_lookup : Primrec₂ lookup := by + have h := Primrec.list_foldr (β := ℕ × Bool) (σ := Option Bool) + (α := ℕ × Assignment) Primrec.snd (Primrec.const none) + (Primrec.ite + (Primrec.eq.comp (Primrec.fst.comp Primrec.fst) + (Primrec.fst.comp (Primrec.fst.comp Primrec.snd))) + (Primrec.option_some.comp (Primrec.snd.comp (Primrec.fst.comp Primrec.snd))) + (Primrec.snd.comp Primrec.snd)).to₂ + apply h.of_eq + rintro ⟨q, xs⟩ + induction xs with + | nil => rfl + | cons p xs ih => simp [lookup, ih] + +theorem primrec_bound : Primrec bound := by + have h := Primrec.list_foldr (β := ℕ × Bool) (σ := ℕ) + (α := Assignment) Primrec.id (Primrec.const 0) + (Primrec.succ.comp (Primrec.nat_add.comp + (Primrec.fst.comp (Primrec.fst.comp Primrec.snd)) + (Primrec.snd.comp Primrec.snd))).to₂ + apply h.of_eq + intro xs + induction xs with + | nil => rfl + | cons p xs ih => + dsimp only at ih + simp only [bound] + exact congrArg (fun n => p.1 + n + 1) ih + +theorem primrec_filler (side : Bool) : Primrec (filler side) := + Primrec.nat_add.comp (Primrec.nat_mul.comp (Primrec.const 2) primrec_bound) + (Primrec.const (if side then 0 else 1)) + +theorem primrec_query (c : Nat.Partrec.Code) (side : Bool) : + Primrec (query c side) := by + have hplan : Primrec (fun s : State => approximate c s.1 s.2.2) := + (primrec_approximate c).comp Primrec.fst (Primrec.snd.comp Primrec.snd) + have hfill : Primrec (fun s : State => filler side s.2.1) := + (primrec_filler side).comp (Primrec.fst.comp Primrec.snd) + have hready : Primrec (fun p : State × Action => + match lookup p.2.1 p.1.2.1 with + | none => p.2.1 + | some _ => filler side p.1.2.1) := + by + apply (Primrec.option_casesOn + (primrec_lookup.comp (Primrec.fst.comp Primrec.snd) + (Primrec.fst.comp (Primrec.snd.comp Primrec.fst))) + (Primrec.fst.comp Primrec.snd) + (hfill.comp (Primrec.fst.comp Primrec.fst)).to₂).of_eq + intro p + cases lookup p.2.1 p.1.2.1 <;> rfl + apply (Primrec.option_casesOn hplan hfill hready.to₂).of_eq + intro s + unfold query + cases approximate c s.1 s.2.2 <;> rfl + +theorem primrec_advance (c : Nat.Partrec.Code) (side : Bool) : + Primrec₂ (advance c side) := by + have hquery : Primrec (fun p : State × Bool => query c side p.1) := + (primrec_query c side).comp Primrec.fst + have hcache : Primrec (fun p : State × Bool => + (query c side p.1, p.2) :: p.1.2.1) := + Primrec.list_cons.comp (hquery.pair Primrec.snd) + (Primrec.fst.comp (Primrec.snd.comp Primrec.fst)) + have hplan : Primrec (fun p : State × Bool => approximate c p.1.1 p.1.2.2) := + (primrec_approximate c).comp (Primrec.fst.comp Primrec.fst) + (Primrec.snd.comp (Primrec.snd.comp Primrec.fst)) + have hwait : Primrec (fun p : State × Bool => + (p.1.1, (query c side p.1, p.2) :: p.1.2.1, p.1.2.2 + 1)) := + (Primrec.fst.comp Primrec.fst).pair + (hcache.pair (Primrec.succ.comp + (Primrec.snd.comp (Primrec.snd.comp Primrec.fst)))) + have hanswer : Primrec (fun p : (State × Bool) × Action => + (lookup p.2.1 p.1.1.2.1).getD p.1.2) := + Primrec.option_getD.comp + (primrec_lookup.comp (Primrec.fst.comp Primrec.snd) + (Primrec.fst.comp (Primrec.snd.comp (Primrec.fst.comp Primrec.fst)))) + (Primrec.snd.comp Primrec.fst) + have hready : Primrec (fun p : (State × Bool) × Action => + (p.1.1.1 ++ [(p.2.1, (lookup p.2.1 p.1.1.2.1).getD p.1.2)], + (query c side p.1.1, p.1.2) :: p.1.1.2.1, 0)) := + (Primrec.list_concat.comp (Primrec.fst.comp (Primrec.fst.comp Primrec.fst)) + ((Primrec.fst.comp Primrec.snd).pair hanswer)).pair + ((hcache.comp Primrec.fst).pair (Primrec.const 0)) + apply (Primrec.option_casesOn hplan hwait hready.to₂).of_eq + intro p + unfold advance + cases approximate c p.1.1 p.1.2.2 <;> rfl + +theorem primrec_state (c : Nat.Partrec.Code) (side : Bool) : + Primrec (state c side) := + Primrec.list_foldl Primrec.id (Primrec.const initial) + ((primrec_advance c side).comp (Primrec.fst.comp Primrec.snd) + (Primrec.snd.comp Primrec.snd)).to₂ + +/-- The simulator's scan is total, primitive recursive, and fresh on every +transcript, whether or not the partial program halts. -/ +def scan (c : Nat.Partrec.Code) (side : Bool) : ScanRule where + query v := query c side (state c side v) + computable_query := ((primrec_query c side).comp (primrec_state c side)).to_comp + fresh v n hn := by + obtain ⟨b, hb⟩ := previous_query_mem c side v n hn + intro h + rw [h] at hb + exact query_not_mem c side (state c side v) b hb + +/-- Every active observation has already been supplied to the simulated +program. Inactive filler observations need not have been supplied yet. -/ +def ActiveCovered (side : Bool) (s : State) : Prop := + ∀ q b, (q, b) ∈ s.2.1 → q.bodd = side → ∃ d, (q, d) ∈ s.1 + +theorem mem_original_advance (c : Nat.Partrec.Code) (side : Bool) + (s : State) (b : Bool) {p : ℕ × Bool} (hp : p ∈ s.1) : + p ∈ (advance c side s b).1 := by + unfold advance + split + · exact hp + · exact List.mem_append_left _ hp + +theorem active_query_ready (c : Nat.Partrec.Code) (side : Bool) (s : State) + (hactive : (query c side s).bodd = side) : + ∃ a, approximate c s.1 s.2.2 = some a ∧ + lookup a.1 s.2.1 = none ∧ query c side s = a.1 := by + cases hp : approximate c s.1 s.2.2 with + | none => + simp [query, hp] at hactive + | some a => + cases hl : lookup a.1 s.2.1 with + | none => exact ⟨a, rfl, hl, by simp [query, hp, hl]⟩ + | some d => + simp [query, hp, hl] at hactive + +theorem activeCovered_advance (c : Nat.Partrec.Code) (side : Bool) + (s : State) (b : Bool) (h : ActiveCovered side s) : + ActiveCovered side (advance c side s b) := by + intro q d hmem hactive + rw [advance_observed] at hmem + rcases List.mem_cons.mp hmem with heq | hmem + · have hq : q = query c side s := congrArg Prod.fst heq + subst q + obtain ⟨a, ha, hl, hq⟩ := active_query_ready c side s hactive + refine ⟨b, ?_⟩ + simp [advance, ha, hl, hq] + · obtain ⟨e, he⟩ := h q d hmem hactive + exact ⟨e, mem_original_advance c side s b he⟩ + +theorem activeCovered_state (c : Nat.Partrec.Code) (side : Bool) (v : List Bool) : + ActiveCovered side (state c side v) := by + induction v using List.reverseRecOn with + | nil => simp [state, initial, ActiveCovered] + | append_singleton v b ih => + rw [state_snoc] + exact activeCovered_advance c side _ b ih + +/-- The concrete simulator state after `n` genuine observations of `X`. -/ +def run (c : Nat.Partrec.Code) (side : Bool) (X : Cantor) (n : ℕ) : State := + state c side ((scan c side).transcript X n) + +@[simp] theorem run_zero (c : Nat.Partrec.Code) (side : Bool) (X : Cantor) : + run c side X 0 = initial := rfl + +theorem run_succ (c : Nat.Partrec.Code) (side : Bool) (X : Cantor) (n : ℕ) : + run c side X (n + 1) = + advance c side (run c side X n) (X (query c side (run c side X n))) := by + simp only [run, ScanRule.transcript_succ, state_snoc] + rfl + +/-- All cached answers are the actual input bits. -/ +theorem run_cache_correct (c : Nat.Partrec.Code) (side : Bool) (X : Cantor) + (n : ℕ) : ∀ q b, (q, b) ∈ (run c side X n).2.1 → b = X q := by + induction n with + | zero => simp [initial] + | succ n ih => + intro q b h + rw [run_succ, advance_observed] at h + rcases List.mem_cons.mp h with heq | h + · exact (congrArg Prod.snd heq).trans (congrArg X (congrArg Prod.fst heq).symm) + · exact ih q b h + +theorem advance_original_ready (c : Nat.Partrec.Code) (side : Bool) (X : Cantor) + (s : State) (hcache : ∀ q b, (q, b) ∈ s.2.1 → b = X q) + {a : Action} (ha : approximate c s.1 s.2.2 = some a) : + (advance c side s (X (query c side s))).1 = s.1 ++ [(a.1, X a.1)] := by + cases hl : lookup a.1 s.2.1 with + | none => simp [advance, query, ha, hl] + | some b => + have hb := hcache a.1 b (mem_of_lookup_eq_some hl) + simp [advance, ha, hl, hb] + +/-- A completed partial computation is eventually acted upon. This theorem +allows arbitrarily long waits, cached-answer replay, and arbitrary intervening +inactive observations. -/ +theorem completes_next (c : Nat.Partrec.Code) (side : Bool) (X : Cantor) + (n budget : ℕ) {a : Action} + (h : approximate c (run c side X n).1 ((run c side X n).2.2 + budget) = some a) : + ∃ m, n < m ∧ (run c side X m).1 = (run c side X n).1 ++ [(a.1, X a.1)] := by + induction budget generalizing n with + | zero => + have ha : approximate c (run c side X n).1 (run c side X n).2.2 = some a := by + simpa using h + refine ⟨n + 1, by omega, ?_⟩ + rw [run_succ] + exact advance_original_ready c side X _ (run_cache_correct c side X n) ha + | succ budget ih => + cases hp : approximate c (run c side X n).1 (run c side X n).2.2 with + | none => + have hw : run c side X (n + 1) = + ((run c side X n).1, + (query c side (run c side X n), X (query c side (run c side X n))) :: + (run c side X n).2.1, + (run c side X n).2.2 + 1) := by + rw [run_succ] + simp [advance, hp] + have hn : approximate c (run c side X (n + 1)).1 + ((run c side X (n + 1)).2.2 + budget) = some a := by + simpa only [hw, Nat.add_assoc, Nat.add_comm 1 budget] using h + obtain ⟨m, hm, hnext⟩ := ih (n + 1) hn + exact ⟨m, by omega, by simpa only [hw] using hnext⟩ + | some b => + have hab := approximate_unique c _ hp h + subst b + refine ⟨n + 1, by omega, ?_⟩ + rw [run_succ] + exact advance_original_ready c side X _ (run_cache_correct c side X n) hp + +/-- The first `n` assignments of a proposed source run. -/ +def sourceAssignment (a : ℕ → Action) (X : Cantor) (n : ℕ) : Assignment := + (List.range n).map fun i => ((a i).1, X (a i).1) + +@[simp] theorem sourceAssignment_zero (a : ℕ → Action) (X : Cantor) : + sourceAssignment a X 0 = [] := rfl + +@[simp] theorem sourceAssignment_succ (a : ℕ → Action) (X : Cantor) (n : ℕ) : + sourceAssignment a X (n + 1) = sourceAssignment a X n ++ [((a n).1, X (a n).1)] := by + simp [sourceAssignment, List.range_succ] + +/-- An infinite fresh run of a partial rational betting program on an input. +The program need not halt away from this input. -/ +structure SourceRun (c : Nat.Partrec.Code) (X : Cantor) where + /-- The successive query positions and rational wagers of this source run. -/ + action : ℕ → Action + halts : ∀ n, ∃ t, approximate c (sourceAssignment action X n) t = some (action n) + fresh : Function.Injective (fun n => (action n).1) + +/-- Every finite stage of an infinite source run is reached by each of the +two total simulators. Thus divergence on other inputs causes no difficulty. -/ +theorem reaches_source_stage (c : Nat.Partrec.Code) (side : Bool) (X : Cantor) + (r : SourceRun c X) (n : ℕ) : + ∃ m, (run c side X m).1 = sourceAssignment r.action X n := by + induction n with + | zero => exact ⟨0, rfl⟩ + | succ n ih => + obtain ⟨m, hm⟩ := ih + obtain ⟨t, ht⟩ := r.halts n + have ha : approximate c (run c side X m).1 ((run c side X m).2.2 + t) = + some (r.action n) := by + rw [hm] + exact approximate_mono c _ (Nat.le_add_left t _) ht + obtain ⟨j, _, hj⟩ := completes_next c side X m t ha + exact ⟨j, by simpa [hm] using hj⟩ + +end Klr.PartialBetting diff --git a/LeanPool/KLRandomness/PartialBettingCapital.lean b/LeanPool/KLRandomness/PartialBettingCapital.lean new file mode 100644 index 0000000000..11cdeee15e --- /dev/null +++ b/LeanPool/KLRandomness/PartialBettingCapital.lean @@ -0,0 +1,400 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.PartialBetting +public import LeanPool.KLRandomness.ComputableRational +import Mathlib.Tactic.Linarith +import Mathlib.Tactic.NormNum +import Mathlib.Tactic.Ring + +/-! +# Capital preservation by the partial-strategy scheduler + +Each parity simulator places exactly the source bets on its active parity and +has zero wager on every other query. Its capital at the stage corresponding to +source stage `n` is therefore the product of the source returns on that parity. +The two parity products multiply to the original capital, so an unbounded +source capital makes at least one total simulator unbounded. +-/ + +@[expose] public section + +namespace Klr.PartialBetting + +open Klr.RationalComputability + +/-- Decode and legalize a rational wager. On an already legal source wager +the clipping has no effect. -/ +def fraction (a : Action) : ℚ := + max (-1) (min 1 ((a.2.1 : ℚ) / (a.2.2 : ℚ))) + +theorem neg_one_le_fraction (a : Action) : -1 ≤ fraction a := le_max_left _ _ + +theorem fraction_le_one (a : Action) : fraction a ≤ 1 := by + exact max_le (by norm_num) (min_le_left _ _) + +theorem fraction_eq_of_legal (a : Action) + (h : |(a.2.1 : ℚ) / (a.2.2 : ℚ)| ≤ 1) : + fraction a = (a.2.1 : ℚ) / (a.2.2 : ℚ) := by + obtain ⟨hl, hu⟩ := abs_le.mp h + simp [fraction, min_eq_right hu, max_eq_right hl] + +/-- The actual stake. Cached actions and inactive queries have zero wager. -/ +def wager (c : Nat.Partrec.Code) (side : Bool) (s : State) : ℚ := + match approximate c s.1 s.2.2 with + | none => 0 + | some a => match lookup a.1 s.2.1 with + | some _ => 0 + | none => if a.1.bodd = side then fraction a else 0 + +theorem wager_bounds (c : Nat.Partrec.Code) (side : Bool) (s : State) : + -1 ≤ wager c side s ∧ wager c side s ≤ 1 := by + unfold wager + split + · norm_num + · split + · norm_num + · split + · exact ⟨neg_one_le_fraction _, fraction_le_one _⟩ + · norm_num + +/-- The multiplicative capital return from one binary wager. -/ +def factor (w : ℚ) (b : Bool) : ℚ := 1 + (if b then 1 else -1) * w + +theorem factor_nonneg {w : ℚ} (hw : -1 ≤ w ∧ w ≤ 1) (b : Bool) : + 0 ≤ factor w b := by + cases b <;> simp [factor] <;> linarith + +theorem factor_false_add_true (w : ℚ) : factor w false + factor w true = 2 := by + simp only [factor, Bool.false_eq_true, ite_false, ite_true] + ring + +/-- Advance the simulation and update the rational capital for one answer. -/ +def accountStep (c : Nat.Partrec.Code) (side : Bool) + (p : State × ℚ) (b : Bool) : State × ℚ := + (advance c side p.1 b, p.2 * factor (wager c side p.1) b) + +/-- The simulation state and capital after a finite answer transcript. -/ +def account (c : Nat.Partrec.Code) (side : Bool) (v : List Bool) : State × ℚ := + v.foldl (accountStep c side) (initial, 1) + +/-- Exact rational capital of the selected parity simulator. -/ +def rationalCapital (c : Nat.Partrec.Code) (side : Bool) (v : List Bool) : ℚ := + (account c side v).2 + +@[simp] theorem account_snoc (c : Nat.Partrec.Code) (side : Bool) + (v : List Bool) (b : Bool) : + account c side (v ++ [b]) = accountStep c side (account c side v) b := by + simp [account, List.foldl_append] + +theorem account_state (c : Nat.Partrec.Code) (side : Bool) (v : List Bool) : + (account c side v).1 = state c side v := by + induction v using List.reverseRecOn with + | nil => rfl + | append_singleton v b ih => simp [accountStep, ih] + +@[simp] theorem rationalCapital_nil (c : Nat.Partrec.Code) (side : Bool) : + rationalCapital c side [] = 1 := rfl + +theorem rationalCapital_snoc (c : Nat.Partrec.Code) (side : Bool) + (v : List Bool) (b : Bool) : + rationalCapital c side (v ++ [b]) = + rationalCapital c side v * factor (wager c side (state c side v)) b := by + simp [rationalCapital, accountStep, account_state] + +theorem rationalCapital_nonneg (c : Nat.Partrec.Code) (side : Bool) (v : List Bool) : + 0 ≤ rationalCapital c side v := by + induction v using List.reverseRecOn with + | nil => norm_num + | append_singleton v b ih => + rw [rationalCapital_snoc] + exact mul_nonneg ih (factor_nonneg (wager_bounds c side _) b) + +theorem rationalCapital_fair (c : Nat.Partrec.Code) (side : Bool) (v : List Bool) : + rationalCapital c side (v ++ [false]) + rationalCapital c side (v ++ [true]) = + 2 * rationalCapital c side v := by + rw [rationalCapital_snoc, rationalCapital_snoc, ← mul_add, factor_false_add_true] + ring + +/-- The total simulator's nonnegative fair capital process. -/ +def capital (c : Nat.Partrec.Code) (side : Bool) : CapitalProcess where + value v := (rationalCapital c side v : ℝ) + initial := by simp + nonneg v := Rat.cast_nonneg.mpr (rationalCapital_nonneg c side v) + fair v := by exact_mod_cast rationalCapital_fair c side v + +/-- Rational capital along the actual simulator run. -/ +def runCapital (c : Nat.Partrec.Code) (side : Bool) (X : Cantor) (n : ℕ) : ℚ := + rationalCapital c side ((scan c side).transcript X n) + +@[simp] theorem runCapital_zero (c : Nat.Partrec.Code) (side : Bool) (X : Cantor) : + runCapital c side X 0 = 1 := rfl + +theorem runCapital_succ (c : Nat.Partrec.Code) (side : Bool) (X : Cantor) (n : ℕ) : + runCapital c side X (n + 1) = runCapital c side X n * + factor (wager c side (run c side X n)) (X (query c side (run c side X n))) := by + simp only [runCapital, ScanRule.transcript_succ, rationalCapital_snoc] + rfl + +/-- The source return factor on the chosen parity and one on the other parity. -/ +def selectedFactor (side : Bool) (a : Action) (b : Bool) : ℚ := + if a.1.bodd = side then factor (fraction a) b else 1 + +theorem selectedFactor_nonneg (side : Bool) (a : Action) (b : Bool) : + 0 ≤ selectedFactor side a b := by + unfold selectedFactor + split + · exact factor_nonneg ⟨neg_one_le_fraction _, fraction_le_one _⟩ _ + · norm_num + +theorem selectedFactor_mul (a : Action) (b : Bool) : + selectedFactor false a b * selectedFactor true a b = factor (fraction a) b := by + unfold selectedFactor + cases a.1.bodd <;> simp + +theorem ready_factor (c : Nat.Partrec.Code) (side : Bool) (X : Cantor) (s : State) + (hcovered : ActiveCovered side s) {a : Action} + (ha : approximate c s.1 s.2.2 = some a) + (hfresh : ∀ d, (a.1, d) ∉ s.1) : + factor (wager c side s) (X (query c side s)) = selectedFactor side a (X a.1) := by + by_cases hs : a.1.bodd = side + · have hl : lookup a.1 s.2.1 = none := by + apply (lookup_eq_none_iff _ _).mpr + intro b hb + obtain ⟨d, hd⟩ := hcovered _ _ hb hs + exact hfresh d hd + simp [wager, query, ha, hl, selectedFactor, hs] + · cases hl : lookup a.1 s.2.1 <;> + simp [wager, query, ha, hl, selectedFactor, hs, factor] + +/-- A source step is completed with exactly its active-parity capital factor. +Waiting and replay add no capital changes. -/ +theorem completes_next_capital (c : Nat.Partrec.Code) (side : Bool) (X : Cantor) + (n budget : ℕ) {a : Action} + (h : approximate c (run c side X n).1 ((run c side X n).2.2 + budget) = some a) + (hfresh : ∀ d, (a.1, d) ∉ (run c side X n).1) : + ∃ m, n < m ∧ + (run c side X m).1 = (run c side X n).1 ++ [(a.1, X a.1)] ∧ + runCapital c side X m = runCapital c side X n * selectedFactor side a (X a.1) := by + induction budget generalizing n with + | zero => + have ha : approximate c (run c side X n).1 (run c side X n).2.2 = some a := by + simpa using h + refine ⟨n + 1, by omega, ?_, ?_⟩ + · rw [run_succ] + exact advance_original_ready c side X _ (run_cache_correct c side X n) ha + · rw [runCapital_succ] + exact congrArg (fun z => runCapital c side X n * z) + (ready_factor c side X _ (activeCovered_state c side _) ha hfresh) + | succ budget ih => + cases hp : approximate c (run c side X n).1 (run c side X n).2.2 with + | none => + have hw : run c side X (n + 1) = + ((run c side X n).1, + (query c side (run c side X n), X (query c side (run c side X n))) :: + (run c side X n).2.1, + (run c side X n).2.2 + 1) := by + rw [run_succ] + simp [advance, hp] + have hn : approximate c (run c side X (n + 1)).1 + ((run c side X (n + 1)).2.2 + budget) = some a := by + simpa only [hw, Nat.add_assoc, Nat.add_comm 1 budget] using h + have hfn : ∀ d, (a.1, d) ∉ (run c side X (n + 1)).1 := by + simpa only [hw] using hfresh + have hc : runCapital c side X (n + 1) = runCapital c side X n := by + simp [runCapital_succ, wager, hp, factor] + obtain ⟨m, hm, hnext, hcap⟩ := ih (n + 1) hn hfn + exact ⟨m, by omega, by simpa only [hw] using hnext, by simpa only [hc] using hcap⟩ + | some b => + have hab := approximate_unique c _ hp h + subst b + refine ⟨n + 1, by omega, ?_, ?_⟩ + · rw [run_succ] + exact advance_original_ready c side X _ (run_cache_correct c side X n) hp + · rw [runCapital_succ] + exact congrArg (fun z => runCapital c side X n * z) + (ready_factor c side X _ (activeCovered_state c side _) hp hfresh) + +/-- The product of all source return factors through the given time. -/ +def sourceCapital {c : Nat.Partrec.Code} {X : Cantor} (r : SourceRun c X) (n : ℕ) : ℚ := + ∏ i ∈ Finset.range n, factor (fraction (r.action i)) (X (r.action i).1) + +/-- The product of the source return factors on positions of the given parity. -/ +def parityCapital {c : Nat.Partrec.Code} {X : Cantor} + (side : Bool) (r : SourceRun c X) (n : ℕ) : ℚ := + ∏ i ∈ Finset.range n, selectedFactor side (r.action i) (X (r.action i).1) + +@[simp] theorem parityCapital_zero {c : Nat.Partrec.Code} {X : Cantor} + (side : Bool) (r : SourceRun c X) : parityCapital side r 0 = 1 := by + simp [parityCapital] + +theorem parityCapital_succ {c : Nat.Partrec.Code} {X : Cantor} + (side : Bool) (r : SourceRun c X) (n : ℕ) : + parityCapital side r (n + 1) = parityCapital side r n * + selectedFactor side (r.action n) (X (r.action n).1) := by + simp [parityCapital, Finset.prod_range_succ] + +theorem parityCapital_nonneg {c : Nat.Partrec.Code} {X : Cantor} + (side : Bool) (r : SourceRun c X) (n : ℕ) : 0 ≤ parityCapital side r n := + Finset.prod_nonneg fun _ _ => selectedFactor_nonneg _ _ _ + +theorem sourceCapital_eq_mul {c : Nat.Partrec.Code} {X : Cantor} + (r : SourceRun c X) (n : ℕ) : + sourceCapital r n = parityCapital false r n * parityCapital true r n := by + simp only [sourceCapital, parityCapital, ← Finset.prod_mul_distrib, selectedFactor_mul] + +theorem source_fresh {c : Nat.Partrec.Code} {X : Cantor} + (r : SourceRun c X) (n : ℕ) (b : Bool) : + ((r.action n).1, b) ∉ sourceAssignment r.action X n := by + intro h + obtain ⟨i, hi, he⟩ := List.mem_map.mp h + have hi' := List.mem_range.mp hi + have hpos : (r.action i).1 = (r.action n).1 := congrArg (fun p : ℕ × Bool => p.1) he + have he' : i = n := r.fresh hpos + omega + +/-- Exact capital simulation, at a possibly much later genuine-query stage. +Both the assignment and the capital agree with the corresponding parity run. -/ +theorem reaches_source_capital (c : Nat.Partrec.Code) (side : Bool) (X : Cantor) + (r : SourceRun c X) (n : ℕ) : + ∃ m, (run c side X m).1 = sourceAssignment r.action X n ∧ + runCapital c side X m = parityCapital side r n := by + induction n with + | zero => exact ⟨0, rfl, by simp⟩ + | succ n ih => + obtain ⟨m, hm, hcap⟩ := ih + obtain ⟨t, ht⟩ := r.halts n + have ha : approximate c (run c side X m).1 ((run c side X m).2.2 + t) = + some (r.action n) := by + rw [hm] + exact approximate_mono c _ (Nat.le_add_left t _) ht + have hfresh : ∀ d, ((r.action n).1, d) ∉ (run c side X m).1 := by + simpa only [hm] using source_fresh r n + obtain ⟨j, _, hj, hjcap⟩ := completes_next_capital c side X m t ha hfresh + refine ⟨j, by simpa [hm] using hj, ?_⟩ + simpa [hcap, parityCapital_succ] using hjcap + +/-- Unbounded capital for an infinite run of a partial rational program. -/ +def SourceRun.Succeeds {c : Nat.Partrec.Code} {X : Cantor} (r : SourceRun c X) : Prop := + ∀ bound : ℝ, ∃ n, bound < (sourceCapital r n : ℝ) + +theorem unbounded_parity {c : Nat.Partrec.Code} {X : Cantor} + (r : SourceRun c X) (hr : r.Succeeds) : + (∀ bound : ℝ, ∃ n, bound < (parityCapital false r n : ℝ)) ∨ + (∀ bound : ℝ, ∃ n, bound < (parityCapital true r n : ℝ)) := by + by_contra! h + obtain ⟨⟨A, hA⟩, ⟨B, hB⟩⟩ := h + obtain ⟨n, hn⟩ := hr (max 0 A * max 0 B) + have hprod : (parityCapital false r n : ℝ) * (parityCapital true r n : ℝ) ≤ + max 0 A * max 0 B := by + apply mul_le_mul ((hA n).trans (le_max_right _ _)) ((hB n).trans (le_max_right _ _)) + · exact_mod_cast parityCapital_nonneg true r n + · exact le_max_left _ _ + have heq : (sourceCapital r n : ℝ) = + (parityCapital false r n : ℝ) * (parityCapital true r n : ℝ) := by + exact_mod_cast sourceCapital_eq_mul r n + rw [← heq] at hprod + exact (not_lt_of_ge hprod) hn + +/-- The two fixed total schedulers cover the success of every infinite fresh +rational-wager run of the source program. -/ +theorem unbounded_simulator {c : Nat.Partrec.Code} {X : Cantor} + (r : SourceRun c X) (hr : r.Succeeds) : + ∃ side : Bool, ∀ bound : ℝ, ∃ n, bound < (runCapital c side X n : ℝ) := by + obtain h | h := unbounded_parity r hr + · refine ⟨false, fun bound => ?_⟩ + obtain ⟨n, hn⟩ := h bound + obtain ⟨m, _, hm⟩ := reaches_source_capital c false X r n + exact ⟨m, by simpa only [hm] using hn⟩ + · refine ⟨true, fun bound => ?_⟩ + obtain ⟨n, hn⟩ := h bound + obtain ⟨m, _, hm⟩ := reaches_source_capital c true X r n + exact ⟨m, by simpa only [hm] using hn⟩ + +theorem primrec_fraction : Primrec fraction := + primrec_rat_max.comp (Primrec.const (-1)) + (primrec_rat_min.comp (Primrec.const 1) + (primrec_rat_div.comp (primrec_rat_intCast.comp (Primrec.fst.comp Primrec.snd)) + (primrec_rat_natCast.comp (Primrec.snd.comp Primrec.snd)))) + +theorem primrec_wager (c : Nat.Partrec.Code) (side : Bool) : Primrec (wager c side) := by + have hplan : Primrec (fun s : State => approximate c s.1 s.2.2) := + (primrec_approximate c).comp Primrec.fst (Primrec.snd.comp Primrec.snd) + have hbet : Primrec (fun p : State × Action => + if p.2.1.bodd = side then fraction p.2 else 0) := + Primrec.ite (Primrec.eq.comp + (Primrec.nat_bodd.comp (Primrec.fst.comp Primrec.snd)) (Primrec.const side)) + (primrec_fraction.comp Primrec.snd) (Primrec.const 0) + have hready : Primrec (fun p : State × Action => + match lookup p.2.1 p.1.2.1 with + | some _ => 0 + | none => if p.2.1.bodd = side then fraction p.2 else 0) := by + apply (Primrec.option_casesOn + (primrec_lookup.comp (Primrec.fst.comp Primrec.snd) + (Primrec.fst.comp (Primrec.snd.comp Primrec.fst))) + hbet (Primrec.const 0).to₂).of_eq + intro p + cases lookup p.2.1 p.1.2.1 <;> rfl + apply (Primrec.option_casesOn hplan (Primrec.const 0) hready.to₂).of_eq + intro s + unfold wager + cases approximate c s.1 s.2.2 <;> rfl + +theorem primrec_factor : Primrec₂ factor := + primrec_rat_add.comp (Primrec.const 1) + (primrec_rat_mul.comp ((Primrec.dom_bool fun b => if b then (1 : ℚ) else -1).comp + Primrec.snd) Primrec.fst) + +theorem primrec_accountStep (c : Nat.Partrec.Code) (side : Bool) : + Primrec₂ (accountStep c side) := + ((primrec_advance c side).comp (Primrec.fst.comp Primrec.fst) Primrec.snd).pair + (primrec_rat_mul.comp (Primrec.snd.comp Primrec.fst) + (primrec_factor.comp ((primrec_wager c side).comp (Primrec.fst.comp Primrec.fst)) + Primrec.snd)) + +theorem primrec_account (c : Nat.Partrec.Code) (side : Bool) : + Primrec (account c side) := + Primrec.list_foldl Primrec.id (Primrec.const (initial, (1 : ℚ))) + ((primrec_accountStep c side).comp (Primrec.fst.comp Primrec.snd) + (Primrec.snd.comp Primrec.snd)).to₂ + +theorem primrec_rationalCapital (c : Nat.Partrec.Code) (side : Bool) : + Primrec (rationalCapital c side) := + Primrec.snd.comp (primrec_account c side) + +/-- The totalized strategy in the repository's original computable-real +interface. Its query and its rational capital are both primitive recursive. -/ +def strategy (c : Nat.Partrec.Code) (side : Bool) : BettingStrategy where + scan := scan c side + capital := capital c side + computable_capital := computableRealCapital_of_rat (primrec_rationalCapital c side).to_comp + +/-- Merkle's two-simulator reduction for partial rational-wager programs. +The pair of total primitive-recursive simulators depends only on the program, +and covers its success on every input admitting an infinite fresh source run. -/ +theorem two_total_strategies_cover {c : Nat.Partrec.Code} {X : Cantor} + (r : SourceRun c X) (hr : r.Succeeds) : + (strategy c false).Succeeds X ∨ (strategy c true).Succeeds X := by + obtain ⟨side, h⟩ := unbounded_simulator r hr + have hs : (strategy c side).Succeeds X := h + cases side + · exact Or.inl hs + · exact Or.inr hs + +/-- Total KL randomness rules out every successful infinite fresh run of a +partial rational-wager program. -/ +theorem no_partial_rational_success {X : Cantor} (hX : KolmogorovLovelandRandom X) + {c : Nat.Partrec.Code} (r : SourceRun c X) : ¬ r.Succeeds := by + intro hr + rcases two_total_strategies_cover r hr with h | h + · exact hX (strategy c false) h + · exact hX (strategy c true) h + +end Klr.PartialBetting diff --git a/LeanPool/KLRandomness/PoolAcceptance.lean b/LeanPool/KLRandomness/PoolAcceptance.lean new file mode 100644 index 0000000000..f4c6e9debc --- /dev/null +++ b/LeanPool/KLRandomness/PoolAcceptance.lean @@ -0,0 +1,153 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.PoolWitness +import Mathlib.Tactic.Linarith + +/-! +# Finite-horizon acceptance from actual limiting pools + +Once the finite advice is fixed, actual eventual pool estimates imply that +some finite horizon passes all three rational tests. The argument uses +convergence only to prove existence; no convergence modulus is an input to +the checker or to the exhaustive search. + +Combining this bridge with weak-limit selection proves that accepted +candidates exist at every sufficiently large pool size. +-/ + +@[expose] public section + +namespace Klr.PoolAdvice + +open MeasureTheory Filter +open scoped Topology BigOperators symmDiff + +/-- The finite weighted test converges to the actual eventual weighted mass +of its fixed pool. -/ +theorem tendsto_weightedMass {π : ℕ → ScanRule} {rules : List ScanRule} + (hπ : ∀ i < rules.length, rules[i]? = some (π i)) + (A : Advice) (G : List ℕ) (hG : G.Nodup) : + Tendsto (fun V : ℕ => (weightedMass rules A G V : ℝ)) atTop + (𝓝 (Pool.finitePoolMass π rules.length G.toFinset)) := by + simp only [weightedMass_eq_sum_integral π hπ A G hG, Pool.advice_weight_cast, + Pool.finitePoolMass] + exact tendsto_finsetSum (Finset.range rules.length) fun i _ => + (PoolQuery.tendsto_integral_readFractionBy (π i) G.toFinset).const_mul (Pool.weight i) + +/-- Final pool estimates with room below the acceptance thresholds give an +actual finite candidate accepted by the exact rational checker. -/ +theorem exists_accepted_of_final_tests {π : ℕ → ScanRule} {rules : List ScanRule} + (hπ : ∀ i < rules.length, rules[i]? = some (π i)) (A : Advice) + (hℓ : A.protectedCount ≤ rules.length) (hε : 0 < (A.error : ℝ)) + {M : ℕ} {G : Finset ℕ} (hcard : G.card = M) + (hposition : ∀ b ∈ G, A.positionBound ≤ b) + (hhigh : ∀ i < A.protectedCount, + fairCoin.real {Z | Z ∈ highSet A i ∧ PoolQuery.readFraction (π i) G Z < 1} < + 2 * (A.error : ℝ)) + (hdist : ∀ i < A.protectedCount, + (∫ Z, |PoolQuery.readFraction (π i) G Z - approx A i Z| ∂fairCoin) < + 2 * (A.error : ℝ)) + (hweighted : (A.threshold : ℝ) < Pool.finitePoolMass π rules.length G) : + ∃ C : Candidate, Accepted rules A M C := by + classical + have hevHigh : ∀ᶠ V : ℕ in atTop, ∀ i : Fin A.protectedCount, + fairCoin.real {Z | Z ∈ highSet A i ∧ PoolQuery.readFractionBy (π i) G V Z < 1} < + 3 * (A.error : ℝ) := by + apply Filter.eventually_all.mpr + intro i + exact (PoolQuery.tendsto_high_missBy (π i) G (measurableSet_highSet A i)).eventually + (p := fun x => x < 3 * (A.error : ℝ)) (gt_mem_nhds (by linarith [hhigh i i.isLt])) + have hevDist : ∀ᶠ V : ℕ in atTop, ∀ i : Fin A.protectedCount, + (∫ Z, |PoolQuery.readFraction (π i) G Z - + PoolQuery.readFractionBy (π i) G V Z| ∂fairCoin) < (A.error : ℝ) := by + exact Filter.eventually_all.mpr fun i => + (PoolQuery.tendsto_readFractionBy_l1 (π i) G).eventually (gt_mem_nhds hε) + have hwlim : Tendsto (fun V : ℕ => (weightedMass rules A G.toList V : ℝ)) atTop + (𝓝 (Pool.finitePoolMass π rules.length G)) := by + simpa only [Finset.toList_toFinset] using + tendsto_weightedMass hπ A G.toList G.nodup_toList + have hevWeight := hwlim.eventually (lt_mem_nhds hweighted) + obtain ⟨V, hVhigh, hVdist, hVweighted⟩ := (hevHigh.and (hevDist.and hevWeight)).exists + refine ⟨(G.toList, V), ?_⟩ + refine ⟨?_, G.nodup_toList, ?_, ?_, ?_, ?_⟩ + · simpa only [Finset.length_toList] using hcard + · intro b hb + exact hposition b (Finset.mem_toList.mp hb) + · intro i hi + have hreal : (highMiss rules A G.toList V i : ℝ) < 3 * (A.error : ℝ) := by + rw [highMiss_eq_measureReal (hπ i (hi.trans_le hℓ)) A G.toList G.nodup_toList V, + Finset.toList_toFinset] + exact hVhigh ⟨i, hi⟩ + exact_mod_cast hreal + · intro i hi + have hsmall : (∫ Z, |PoolQuery.readFractionBy (π i) G V Z - + PoolQuery.readFraction (π i) G Z| ∂fairCoin) < (A.error : ℝ) := by + simpa only [abs_sub_comm] using hVdist ⟨i, hi⟩ + have htri := PoolSoundness.integral_abs_sub_le_add + (PoolQuery.integrable_readFractionBy (π i) G V) + (PoolQuery.integrable_readFraction (π i) G) (integrable_approx A i) + have hfinal := hdist i hi + have hreal : (distance rules A G.toList V i : ℝ) < 3 * (A.error : ℝ) := by + rw [distance_eq_integral (hπ i (hi.trans_le hℓ)) A G.toList G.nodup_toList V, + Finset.toList_toFinset] + linarith + exact_mod_cast hreal + · exact_mod_cast hVweighted + +end Klr.PoolAdvice + +namespace Klr.Pool.QueryPartition + +open MeasureTheory Filter +open scoped Topology BigOperators symmDiff + +/-- Fixed Borel and rational advice, together with the actual query weak +limits, ensures that accepted finite candidates exist for every sufficiently +large size. -/ +theorem eventually_exists_accepted {π : ℕ → ScanRule} {a : ℕ → ℕ} + (D : QueryPartition π a) (ha : Tendsto D.position atTop atTop) + (rules : List ScanRule) (hπ : ∀ i < rules.length, rules[i]? = some (π i)) + (A : PoolAdvice.Advice) (hℓ : A.protectedCount ≤ rules.length) + (hε : 0 < (A.error : ℝ)) + (hhigh : ∀ i < A.protectedCount, + fairCoin.real (D.high i ∆ PoolAdvice.highSet A i) < (A.error : ℝ)) + (happrox : ∀ i < A.protectedCount, + (∫ Z, |PoolAdvice.approx A i Z - D.representative i Z| ∂fairCoin) < (A.error : ℝ)) + (hweighted : ∀ᶠ n : ℕ in atTop, + (A.threshold : ℝ) < ∑ i ∈ Finset.range rules.length, + weight i * queryProbability (π i) (D.position n)) : + ∀ᶠ M : ℕ in atTop, ∃ C : PoolAdvice.Candidate, PoolAdvice.Accepted rules A M C := by + filter_upwards [D.eventually_exists_final_pool ha A.protectedCount rules.length + A.positionBound hε hweighted] with M hM + obtain ⟨G, hcard, hposition, hGhigh, hGdist, hGweighted⟩ := hM + apply PoolAdvice.exists_accepted_of_final_tests hπ A hℓ hε hcard hposition + (hweighted := hGweighted) + · intro i hi + have hsub : {Z | Z ∈ PoolAdvice.highSet A i ∧ PoolQuery.readFraction (π i) G Z < 1} ⊆ + (D.high i ∆ PoolAdvice.highSet A i) ∪ + {Z | Z ∈ D.high i ∧ PoolQuery.readFraction (π i) G Z < 1} := by + intro Z hZ + by_cases hz : Z ∈ D.high i + · exact Or.inr ⟨hz, hZ.2⟩ + · exact Or.inl (Or.inr ⟨hZ.1, hz⟩) + have hle := (measureReal_mono hsub (measure_ne_top fairCoin _)).trans + (measureReal_union_le (μ := fairCoin) _ _) + linarith [hhigh i hi, hGhigh i hi] + · intro i hi + have hrep : Integrable (D.representative i) fairCoin := + (integrable_L2 (D.limit i)).congr (D.representative_ae_eq i).symm + have htri := PoolSoundness.integral_abs_sub_le_add + (PoolQuery.integrable_readFraction (π i) G) hrep (PoolAdvice.integrable_approx A i) + have happ : (∫ Z, |D.representative i Z - PoolAdvice.approx A i Z| ∂fairCoin) < + (A.error : ℝ) := by simpa only [abs_sub_comm] using happrox i hi + linarith [hGdist i hi] + +end Klr.Pool.QueryPartition diff --git a/LeanPool/KLRandomness/PoolAdvice.lean b/LeanPool/KLRandomness/PoolAdvice.lean new file mode 100644 index 0000000000..c2e1f0d2d7 --- /dev/null +++ b/LeanPool/KLRandomness/PoolAdvice.lean @@ -0,0 +1,152 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.SparseListSearchComputable + +/-! +# Finite advice and the three finite pool tests + +All functions in this file act on finite answer words. A scan is fed the +successive prefixes of that word; these are not the scan's input-space +transcripts. The finite advice is chosen once, before the requested pool size. +The associated computability and exhaustive-search theorems are in +`PoolAdviceComputable` and `PoolSearch`. +-/ + +@[expose] public section + +namespace Klr.PoolAdvice + +open SparseSearch + +/-- A fixed finite list of total scans has a total query dispatcher. Indices +outside the list are harmlessly assigned the constant-zero query. -/ +def query : List ScanRule → ℕ → List Bool → ℕ + | [], _, _ => 0 + | π :: _, 0, s => π.query s + | _ :: ps, i + 1, s => query ps i s + +theorem query_of_getElem? {rules : List ScanRule} {i : ℕ} {π : ScanRule} + (hi : rules[i]? = some π) (s : List Bool) : query rules i s = π.query s := by + induction rules generalizing i with + | nil => simp at hi + | cons ρ rules ih => + cases i with + | zero => simp only [List.getElem?_cons_zero, Option.some.injEq] at hi; subst ρ; rfl + | succ i => exact ih (by simpa using hi) + +/-- One Boolean table and one rational table, indexed by ordinary encodings +of finite binary prefixes. The default values allow arbitrary finite tables. -/ +abbrev Table := List Bool × List ℚ + +/-- Exactly the finite data hard-coded into a pool search. `protectedCount` +corresponds to ℓ, and the length of the separately fixed scan list to D. -/ +structure Advice where + /-- Finite bound on positions that the existing construction needs to avoid. -/ + positionBound : ℕ + /-- Number of scans protected by the advice. -/ + protectedCount : ℕ + /-- Length of the input prefixes used for the clopen approximations. -/ + depth : ℕ + /-- Rational tolerance used by the finite pool search. -/ + error : ℚ + /-- Rational threshold used to separate the approximating tables. -/ + threshold : ℚ + /-- The finite clopen tables for the protected scans and partitions. -/ + tables : List Table + +/-- The clopen approximation is determined by one finite prefix. -/ +def highTable (A : Advice) (i : ℕ) (s : List Bool) : Bool := + ((A.tables.getD i ([], [])).1).getD (Encodable.encode (s.take A.depth)) false + +/-- The rational-valued cylinder approximation uses the same finite prefix. -/ +def approxTable (A : Advice) (i : ℕ) (s : List Bool) : ℚ := + ((A.tables.getD i ([], [])).2).getD (Encodable.encode (s.take A.depth)) 0 + +/-- Whether a fixed scan queries a position in its first `V` steps. -/ +def readsBefore (rules : List ScanRule) (i a V : ℕ) (s : List Bool) : Bool := + (List.range V).any fun t => decide (query rules i (s.take t) = a) + +theorem readsBefore_eq_true (rules : List ScanRule) (i a V : ℕ) (s : List Bool) : + readsBefore rules i a V s = true ↔ + ∃ t < V, query rules i (s.take t) = a := by + simp [readsBefore, List.any_eq_true] + +/-- Fraction of the listed pool read by the finite horizon. Repetitions count +with multiplicity here; the acceptance predicate separately checks nodup. -/ +def finiteReads (rules : List ScanRule) (i : ℕ) (G : List ℕ) (V : ℕ) + (s : List Bool) : ℚ := + (G.countP (fun a => readsBefore rules i a V s) : ℚ) / G.length + +/-- Exact uniform expectation of a rational function of `n` fair bits. -/ +def average (n : ℕ) (f : List Bool → ℚ) : ℚ := + ((words n).map f).sum / (2 : ℚ) ^ n + +/-- Common cylinder depth for advice and the finite scan computation. -/ +def testDepth (A : Advice) (V : ℕ) : ℕ := max V A.depth + +/-- Finite approximation to the measure of the high-set points missing a +member of the pool. -/ +def highMiss (rules : List ScanRule) (A : Advice) (G : List ℕ) (V i : ℕ) : ℚ := + average (testDepth A V) fun s => + if highTable A i s && decide (finiteReads rules i G V s < 1) then 1 else 0 + +/-- Exact finite L1 distance from the rational cylinder advice. -/ +def distance (rules : List ScanRule) (A : Advice) (G : List ℕ) (V i : ℕ) : ℚ := + average (testDepth A V) fun s => + |finiteReads rules i G V s - approxTable A i s| + +/-- The paper numbers scans from one; our zero-based scan i has weight +`(1/2)^(i+1)`. -/ +def weight (i : ℕ) : ℚ := (1 / 2 : ℚ) ^ (i + 1) + +/-- Weighted finite-time read mass of all D fixed scans. -/ +def weightedMass (rules : List ScanRule) (A : Advice) (G : List ℕ) (V : ℕ) : ℚ := + ((List.range rules.length).map fun i => + weight i * average (testDepth A V) (finiteReads rules i G V)).sum + +/-- A candidate is a finite pool and a finite scan horizon. -/ +abbrev Candidate := List ℕ × ℕ + +/-- The exact mathematical specification of the finite checker. This contains +no limiting functions, Borel sets, convergence moduli, or oracle calls. -/ +def Accepted (rules : List ScanRule) (A : Advice) (M : ℕ) (C : Candidate) : Prop := + C.1.length = M ∧ C.1.Nodup ∧ + (∀ a ∈ C.1, A.positionBound ≤ a) ∧ + (∀ i < A.protectedCount, highMiss rules A C.1 C.2 i < 3 * A.error) ∧ + (∀ i < A.protectedCount, distance rules A C.1 C.2 i < 3 * A.error) ∧ + A.threshold < weightedMass rules A C.1 C.2 + +@[simp] theorem length_words (n : ℕ) : (words n).length = 2 ^ n := by + induction n with + | zero => simp [words] + | succ n ih => simp [words, ih, pow_succ]; omega + +theorem nodup_words (n : ℕ) : (words n).Nodup := by + induction n with + | zero => simp [words] + | succ n ih => + apply List.Nodup.append (ih.map (fun _ _ h => List.cons.inj h |>.2)) + (ih.map (fun _ _ h => List.cons.inj h |>.2)) + intro s hs ht + obtain ⟨u, _, hu⟩ := List.mem_map.mp hs + obtain ⟨v, _, hv⟩ := List.mem_map.mp ht + rw [← hu] at hv + cases hv + +/-- The exact prefix interpretation of the finite high-set advice. -/ +def highSet (A : Advice) (i : ℕ) : Set Cantor := + {Z | highTable A i (ScanRule.inputPrefix Z A.depth) = true} + +/-- The exact prefix interpretation of the finite rational advice. -/ +def approx (A : Advice) (i : ℕ) (Z : Cantor) : ℝ := + approxTable A i (ScanRule.inputPrefix Z A.depth) + +end Klr.PoolAdvice diff --git a/LeanPool/KLRandomness/PoolAdviceComputable.lean b/LeanPool/KLRandomness/PoolAdviceComputable.lean new file mode 100644 index 0000000000..5f004e1e05 --- /dev/null +++ b/LeanPool/KLRandomness/PoolAdviceComputable.lean @@ -0,0 +1,219 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.PoolAdvice + +/-! +# Computability of the finite pool tests + +A finite list of total computable scans is fixed before the requested pool +size. List induction compiles that family to a single total query dispatcher. +The tests then use only bounded loops, exact rational arithmetic, and the +finite advice tables. No code for a weak limit or a Borel partition is assumed. +-/ + +@[expose] public section + +namespace Klr.PoolAdvice + +open SparseSearch SparseListSearch RationalComputability + +theorem computable_query (rules : List ScanRule) : Computable₂ (query rules) := by + induction rules with + | nil => exact Computable.const 0 + | cons π rules ih => + have hh : Computable₂ (fun p : ℕ × List Bool => fun i => query rules i p.2) := + ih.comp Computable.snd (Computable.snd.comp Computable.fst) + have h := Computable.nat_casesOn Computable.fst + (π.computable_query.comp Computable.snd) hh + exact h.of_eq fun p => by cases p.1 <;> rfl + +/-- A rational bounded sum, used to retain the external parameters in finite +summation of a merely computable (not necessarily primitive recursive) term. -/ +def boundedSum (f : ℕ → ℚ) : ℕ → ℚ + | 0 => 0 + | n + 1 => boundedSum f n + f n + +theorem boundedSum_succ_shift (f : ℕ → ℚ) (n : ℕ) : + boundedSum f (n + 1) = f 0 + boundedSum (fun i => f (i + 1)) n := by + induction n with + | zero => simp [boundedSum] + | succ n ih => rw [boundedSum, ih, boundedSum, add_assoc] + +theorem boundedSum_getD {β : Type*} (f : β → ℚ) (l : List β) (d : β) : + boundedSum (fun i => f (l.getD i d)) l.length = (l.map f).sum := by + induction l with + | nil => rfl + | cons b l ih => + rw [List.length_cons, boundedSum_succ_shift] + simpa only [List.getD_cons_zero, List.getD_cons_succ, List.map_cons, List.sum_cons] using + congrArg (fun q => f b + q) ih + +theorem computable_boundedSum {α : Type*} [Primcodable α] {f : α → ℕ → ℚ} + (hf : Computable₂ f) : Computable (fun a : α × ℕ => boundedSum (f a.1) a.2) := by + have ha : Computable (fun a : (α × ℕ) × (ℕ × ℚ) => a.1.1) := + Computable.fst.comp Computable.fst + have hi : Computable (fun a : (α × ℕ) × (ℕ × ℚ) => a.2.1) := + Computable.fst.comp Computable.snd + have hq : Computable (fun a : (α × ℕ) × (ℕ × ℚ) => a.2.2) := + Computable.snd.comp Computable.snd + have hs := primrec_rat_add.to_comp.comp hq (hf.comp ha hi) + apply (Computable.nat_rec Computable.snd (Computable.const 0) hs.to₂).of_eq + intro a + induction a.2 with + | zero => rfl + | succ n ih => + simpa only [boundedSum, Nat.rec_add_one] using congrArg (fun q => q + f a.1 n) ih + +/-- Rational summation of computable terms along a computable finite list. -/ +theorem computable_list_sum {α β : Type*} [Primcodable α] [Primcodable β] + [Inhabited β] {l : α → List β} {f : α → β → ℚ} + (hl : Computable l) (hf : Computable₂ f) : + Computable (fun a => ((l a).map (f a)).sum) := by + have hg : Computable (fun a : α × ℕ => (l a.1).getD a.2 default) := + (Primrec.list_getD default).to_comp.comp (hl.comp Computable.fst) Computable.snd + have hc := (computable_boundedSum + (f := fun a i => f a ((l a).getD i default)) (hf.comp Computable.fst hg)).comp + (Computable.id.pair (Computable.list_length.comp hl)) + exact hc.of_eq fun a => boundedSum_getD (f a) (l a) default + +theorem computable_rat_abs : Computable (fun q : ℚ => |q|) := + (primrec_rat_max.to_comp.comp Computable.id primrec_rat_neg.to_comp).of_eq + fun _ => abs_eq_max_neg.symm + +theorem computable_rat_lt : Computable₂ (fun p q : ℚ => decide (p < q)) := by + have h := Primrec.not.to_comp.comp + (primrec_rat_le.decide.to_comp.comp Computable.snd Computable.fst) + exact h.of_eq fun p => by + by_cases hp : p.2 ≤ p.1 + · simp [hp, not_lt_of_ge hp] + · simp [hp, lt_of_not_ge hp] + +/-- Exact averaging over the full binary tree at a computable depth is computable. -/ +theorem computable_average {α : Type*} [Primcodable α] {n : α → ℕ} + {f : α → List Bool → ℚ} (hn : Computable n) (hf : Computable₂ f) : + Computable (fun a => average (n a) (f a)) := by + have hw := computable_words.comp hn + have hs := computable_list_sum hw hf + have hd := primrec_rat_natCast.to_comp.comp (Computable.list_length.comp hw) + exact (primrec_rat_div.to_comp.comp hs hd).of_eq fun a => by + simp [average, length_words] + +/-- Fixed Boolean prefix tables are computable without any membership oracle. -/ +theorem computable_highTable (A : Advice) {α : Type*} [Primcodable α] + {i : α → ℕ} {s : α → List Bool} (hi : Computable i) (hs : Computable s) : + Computable (fun a => highTable A (i a) (s a)) := by + have ht := (Primrec.list_getD ([], [])).to_comp.comp (Computable.const A.tables) hi + have hk := Computable.encode.comp (Primrec.list_take.to_comp.comp (Computable.const A.depth) hs) + exact (Primrec.list_getD false).to_comp.comp (Computable.fst.comp ht) hk + +theorem computable_approxTable (A : Advice) {α : Type*} [Primcodable α] + {i : α → ℕ} {s : α → List Bool} (hi : Computable i) (hs : Computable s) : + Computable (fun a => approxTable A (i a) (s a)) := by + have ht := (Primrec.list_getD ([], [])).to_comp.comp (Computable.const A.tables) hi + have hk := Computable.encode.comp (Primrec.list_take.to_comp.comp (Computable.const A.depth) hs) + exact (Primrec.list_getD 0).to_comp.comp (Computable.snd.comp ht) hk + +theorem computable_readsBefore (rules : List ScanRule) {α : Type*} [Primcodable α] + {i a V : α → ℕ} {s : α → List Bool} + (hi : Computable i) (ha : Computable a) (hV : Computable V) (hs : Computable s) : + Computable (fun p => readsBefore rules (i p) (a p) (V p) (s p)) := by + have hp := Primrec.list_take.to_comp.comp Computable.snd (hs.comp Computable.fst) + have hq := (computable_query rules).comp (hi.comp Computable.fst) hp + have he := Primrec.eq.decide.to_comp.comp hq (ha.comp Computable.fst) + exact computable_list_any (p := fun p t => decide (query rules (i p) ((s p).take t) = a p)) + (Primrec.list_range.to_comp.comp hV) he + +theorem computable_finiteReads (rules : List ScanRule) {α : Type*} [Primcodable α] + {i : α → ℕ} {G : α → List ℕ} {V : α → ℕ} {s : α → List Bool} + (hi : Computable i) (hG : Computable G) (hV : Computable V) (hs : Computable s) : + Computable (fun p => finiteReads rules (i p) (G p) (V p) (s p)) := by + have hb := computable_readsBefore rules (hi.comp Computable.fst) Computable.snd + (hV.comp Computable.fst) (hs.comp Computable.fst) + have hc := computable_list_countP (p := fun p a => readsBefore rules (i p) a (V p) (s p)) hG hb + exact primrec_rat_div.to_comp.comp (primrec_rat_natCast.to_comp.comp hc) + (primrec_rat_natCast.to_comp.comp (Computable.list_length.comp hG)) + +theorem computable_testDepth (A : Advice) : Computable (testDepth A) := + Primrec.nat_max.to_comp.comp Computable.id (Computable.const A.depth) + +theorem computable_highMiss (rules : List ScanRule) (A : Advice) : + Computable (fun p : Candidate × ℕ => highMiss rules A p.1.1 p.1.2 p.2) := by + have hG : Computable (fun p : (Candidate × ℕ) × List Bool => p.1.1.1) := + Computable.fst.comp (Computable.fst.comp Computable.fst) + have hV : Computable (fun p : (Candidate × ℕ) × List Bool => p.1.1.2) := + Computable.snd.comp (Computable.fst.comp Computable.fst) + have hi : Computable (fun p : (Candidate × ℕ) × List Bool => p.1.2) := + Computable.snd.comp Computable.fst + have hv := computable_finiteReads rules hi hG hV Computable.snd + have hH := computable_highTable A hi Computable.snd + have hm := Primrec.and.to_comp.comp hH + (computable_rat_lt.comp hv (Computable.const 1)) + have hf := Computable.cond hm (Computable.const (1 : ℚ)) (Computable.const 0) + have hn : Computable (fun p : Candidate × ℕ => testDepth A p.1.2) := + (computable_testDepth A).comp (Computable.snd.comp Computable.fst) + exact (computable_average + (n := fun p : Candidate × ℕ => testDepth A p.1.2) + (f := fun p : Candidate × ℕ => fun s => + cond (highTable A p.2 s && decide (finiteReads rules p.2 p.1.1 p.1.2 s < 1)) + (1 : ℚ) 0) hn hf).of_eq fun _ => by simp [highMiss, Bool.cond_eq_ite] + +theorem computable_distance (rules : List ScanRule) (A : Advice) : + Computable (fun p : Candidate × ℕ => distance rules A p.1.1 p.1.2 p.2) := by + have hG : Computable (fun p : (Candidate × ℕ) × List Bool => p.1.1.1) := + Computable.fst.comp (Computable.fst.comp Computable.fst) + have hV : Computable (fun p : (Candidate × ℕ) × List Bool => p.1.1.2) := + Computable.snd.comp (Computable.fst.comp Computable.fst) + have hi : Computable (fun p : (Candidate × ℕ) × List Bool => p.1.2) := + Computable.snd.comp Computable.fst + have hv := computable_finiteReads rules hi hG hV Computable.snd + have hψ := computable_approxTable A hi Computable.snd + have hf := computable_rat_abs.comp (primrec_rat_sub.to_comp.comp hv hψ) + have hn : Computable (fun p : Candidate × ℕ => testDepth A p.1.2) := + (computable_testDepth A).comp (Computable.snd.comp Computable.fst) + exact computable_average + (n := fun p : Candidate × ℕ => testDepth A p.1.2) + (f := fun p : Candidate × ℕ => fun s => + |finiteReads rules p.2 p.1.1 p.1.2 s - approxTable A p.2 s|) hn hf + +theorem computable_weight : Computable weight := by + have hs : Computable₂ (fun (_ : ℕ) (p : ℕ × ℚ) => p.2 * (1 / 2)) := + (primrec_rat_mul.to_comp.comp (Computable.snd.comp Computable.snd) + (Computable.const (1 / 2))).to₂ + apply (Computable.nat_rec Computable.id (Computable.const (1 / 2 : ℚ)) hs).of_eq + intro i + induction i with + | zero => simp [weight] + | succ i ih => + simpa only [weight, pow_succ, Nat.rec_add_one, id_eq] using + congrArg (fun q : ℚ => q * (1 / 2)) ih + +theorem computable_weightedMass (rules : List ScanRule) (A : Advice) : + Computable (fun C : Candidate => weightedMass rules A C.1 C.2) := by + have hG : Computable (fun p : (Candidate × ℕ) × List Bool => p.1.1.1) := + Computable.fst.comp (Computable.fst.comp Computable.fst) + have hV : Computable (fun p : (Candidate × ℕ) × List Bool => p.1.1.2) := + Computable.snd.comp (Computable.fst.comp Computable.fst) + have hi : Computable (fun p : (Candidate × ℕ) × List Bool => p.1.2) := + Computable.snd.comp Computable.fst + have hv := computable_finiteReads rules hi hG hV Computable.snd + have hn : Computable (fun p : Candidate × ℕ => testDepth A p.1.2) := + (computable_testDepth A).comp (Computable.snd.comp Computable.fst) + have ha := computable_average + (n := fun p : Candidate × ℕ => testDepth A p.1.2) + (f := fun p : Candidate × ℕ => finiteReads rules p.2 p.1.1 p.1.2) hn hv + have hf := primrec_rat_mul.to_comp.comp (computable_weight.comp Computable.snd) ha + exact computable_list_sum + (l := fun _ : Candidate => List.range rules.length) + (f := fun C : Candidate => fun i => + weight i * average (testDepth A C.2) (finiteReads rules i C.1 C.2)) + (Computable.const (List.range rules.length)) hf + +end Klr.PoolAdvice diff --git a/LeanPool/KLRandomness/PoolAdviceMeasure.lean b/LeanPool/KLRandomness/PoolAdviceMeasure.lean new file mode 100644 index 0000000000..528d9cc2ae --- /dev/null +++ b/LeanPool/KLRandomness/PoolAdviceMeasure.lean @@ -0,0 +1,249 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.PoolAdvice +public import LeanPool.KLRandomness.PoolQuery +public import Mathlib.MeasureTheory.Order.Group.Lattice + +/-! +# Exact measure interpretation of the finite pool tests + +The rational averages used by the pool verifier are the fair-coin integrals +of the actual finite-horizon query fractions and finite-prefix advice. This +file connects the executable checker to the Borel probability space. +-/ + +@[expose] public section + +namespace Klr.PoolAdvice + +open MeasureTheory SparseSearch +open scoped BigOperators + +theorem inputPrefix_eq_iff_mem_cylinder (Z : Cantor) (n : ℕ) (s : List Bool) + (hs : s.length = n) : + ScanRule.inputPrefix Z n = s ↔ Z ∈ cylinder s := by + constructor + · intro h + rw [← h] + exact ScanRule.mem_cylinder_inputPrefix Z n + · intro h + apply List.ext_getElem (by simp [hs]) + intro i hi hj + rw [← List.getD_eq_getElem _ false hi, ← List.getD_eq_getElem _ false hj] + exact (ScanRule.getD_inputPrefix Z (by simpa using hi)).trans (h i hj) + +theorem inputPrefix_take (Z : Cantor) {n d : ℕ} (hd : d ≤ n) : + (ScanRule.inputPrefix Z n).take d = ScanRule.inputPrefix Z d := by + simpa only [ScanRule.monotone_transcript] using ScanRule.monotone.transcript_take Z hd + +/-- A function of a finite prefix is exactly a finite cylinder-simple function. -/ +theorem prefixFunction_eq_sum (n : ℕ) (f : List Bool → ℝ) : + (fun Z : Cantor => f (ScanRule.inputPrefix Z n)) = + fun Z => ∑ s ∈ (words n).toFinset, (cylinder s).indicator (fun _ => f s) Z := by + classical + funext Z + have hm : ScanRule.inputPrefix Z n ∈ (words n).toFinset := by + simp [mem_words_iff] + rw [Finset.sum_eq_single (ScanRule.inputPrefix Z n)] + · exact (Set.indicator_of_mem (ScanRule.mem_cylinder_inputPrefix Z n) + (fun _ : Cantor => f (ScanRule.inputPrefix Z n))).symm + · intro s hs hne + have hlen : s.length = n := (mem_words_iff n s).mp (List.mem_toFinset.mp hs) + have hn : Z ∉ cylinder s := by + intro hz + exact hne ((inputPrefix_eq_iff_mem_cylinder Z n s hlen).mpr hz).symm + simp [hn] + · exact fun hn => False.elim (hn hm) + +theorem integrable_prefixFunction (n : ℕ) (f : List Bool → ℝ) : + Integrable (fun Z : Cantor => f (ScanRule.inputPrefix Z n)) fairCoin := by + rw [prefixFunction_eq_sum] + exact integrable_finsetSum _ fun s _ => + (integrable_const (f s)).indicator (measurableSet_cylinder s) + +/-- Uniform finite averaging agrees exactly with fair-coin integration. -/ +theorem integral_prefixFunction (n : ℕ) (f : List Bool → ℝ) : + (∫ Z : Cantor, f (ScanRule.inputPrefix Z n) ∂fairCoin) = + ((words n).map f).sum / (2 : ℝ) ^ n := by + classical + rw [prefixFunction_eq_sum, integral_finsetSum _ fun s _ => + (integrable_const (f s)).indicator (measurableSet_cylinder s)] + rw [← List.sum_toFinset f (nodup_words n), Finset.sum_div] + apply Finset.sum_congr rfl + intro s hs + have hlen : s.length = n := (mem_words_iff n s).mp (List.mem_toFinset.mp hs) + rw [integral_indicator_const _ (measurableSet_cylinder s)] + simp [measureReal_def, hlen, ENNReal.toReal_pow, + smul_eq_mul, div_eq_mul_inv, mul_comm] + +theorem average_eq_integral (n : ℕ) (f : List Bool → ℚ) : + (average n f : ℝ) = + ∫ Z : Cantor, (f (ScanRule.inputPrefix Z n) : ℝ) ∂fairCoin := by + rw [integral_prefixFunction n (fun s => (f s : ℝ))] + simp [average, Rat.cast_list_sum, List.map_map, Function.comp_def] + +theorem measurableSet_highSet (A : Advice) (i : ℕ) : MeasurableSet (highSet A i) := by + have hm : Measurable (fun Z => highTable A i (ScanRule.inputPrefix Z A.depth)) := by + simpa only [ScanRule.monotone_transcript] using + DropEvents.measurable_transcript_eval ScanRule.monotone A.depth (highTable A i) + exact hm (measurableSet_singleton true) + +theorem measurable_approx (A : Advice) (i : ℕ) : Measurable (approx A i) := by + change Measurable (fun Z : Cantor => (approxTable A i (ScanRule.inputPrefix Z A.depth) : ℝ)) + simpa only [ScanRule.monotone_transcript] using + DropEvents.measurable_transcript_eval ScanRule.monotone A.depth + (fun s => (approxTable A i s : ℝ)) + +theorem integrable_approx (A : Advice) (i : ℕ) : Integrable (approx A i) fairCoin := + integrable_prefixFunction A.depth (fun s => (approxTable A i s : ℝ)) + +theorem readsBefore_inputPrefix {rules : List ScanRule} {i : ℕ} {π : ScanRule} + (hi : rules[i]? = some π) (a V n : ℕ) (hV : V ≤ n) (Z : Cantor) : + readsBefore rules i a V (ScanRule.inputPrefix Z n) = true ↔ + PoolQuery.ReadsBy π a V Z := by + rw [readsBefore_eq_true] + unfold PoolQuery.ReadsBy PoolQuery.queryAt + constructor <;> rintro ⟨t, ht, h⟩ <;> refine ⟨t, ht, ?_⟩ + · simpa only [inputPrefix_take Z (ht.le.trans hV), query_of_getElem? hi] using h + · simpa only [inputPrefix_take Z (ht.le.trans hV), query_of_getElem? hi] using h + +private theorem cast_countP_eq_sum (G : List ℕ) (p : ℕ → Bool) : + (G.countP p : ℝ) = (G.map (fun a => if p a then (1 : ℝ) else 0)).sum := by + induction G with + | nil => simp + | cons a G ih => cases hp : p a <;> simp [hp, ih, add_comm] + +/-- The rational count is exactly the actual finite-horizon coverage fraction. -/ +theorem finiteReads_eq_readFractionBy {rules : List ScanRule} {i : ℕ} {π : ScanRule} + (hi : rules[i]? = some π) (G : List ℕ) (hG : G.Nodup) + (V n : ℕ) (hV : V ≤ n) (Z : Cantor) : + (finiteReads rules i G V (ScanRule.inputPrefix Z n) : ℝ) = + PoolQuery.readFractionBy π G.toFinset V Z := by + classical + unfold finiteReads PoolQuery.readFractionBy + push_cast + rw [List.toFinset_card_of_nodup hG, cast_countP_eq_sum, ← List.sum_toFinset _ hG] + congr 1 + apply Finset.sum_congr rfl + intro a ha + have he := readsBefore_inputPrefix hi a V n hV Z + by_cases h : PoolQuery.ReadsBy π a V Z + · simp [PoolQuery.indicatorBy, h, he.mpr h] + · have hn : readsBefore rules i a V (ScanRule.inputPrefix Z n) = false := + Bool.eq_false_iff.mpr (fun ht => h (he.mp ht)) + simp [PoolQuery.indicatorBy, h, hn] + +theorem highTable_inputPrefix (A : Advice) (i n : ℕ) (hd : A.depth ≤ n) (Z : Cantor) : + highTable A i (ScanRule.inputPrefix Z n) = + highTable A i (ScanRule.inputPrefix Z A.depth) := by + simp only [highTable, inputPrefix_take Z hd, inputPrefix_take Z le_rfl] + +theorem approxTable_inputPrefix (A : Advice) (i n : ℕ) (hd : A.depth ≤ n) (Z : Cantor) : + approxTable A i (ScanRule.inputPrefix Z n) = + approxTable A i (ScanRule.inputPrefix Z A.depth) := by + simp only [approxTable, inputPrefix_take Z hd, inputPrefix_take Z le_rfl] + +/-- Exact interpretation of the L1 acceptance test. -/ +theorem distance_eq_integral {rules : List ScanRule} {i : ℕ} {π : ScanRule} + (hi : rules[i]? = some π) (A : Advice) (G : List ℕ) (hG : G.Nodup) (V : ℕ) : + (distance rules A G V i : ℝ) = + ∫ Z, |PoolQuery.readFractionBy π G.toFinset V Z - approx A i Z| ∂fairCoin := by + rw [distance, average_eq_integral] + apply integral_congr_ae + filter_upwards [] with Z + push_cast + rw [finiteReads_eq_readFractionBy hi G hG V (testDepth A V) (Nat.le_max_left _ _) Z, + approxTable_inputPrefix A i (testDepth A V) (Nat.le_max_right _ _) Z] + rfl + +/-- Exact interpretation of the high-set missed-mass acceptance test. -/ +theorem highMiss_eq_measureReal {rules : List ScanRule} {i : ℕ} {π : ScanRule} + (hi : rules[i]? = some π) (A : Advice) (G : List ℕ) (hG : G.Nodup) (V : ℕ) : + (highMiss rules A G V i : ℝ) = + fairCoin.real {Z | Z ∈ highSet A i ∧ PoolQuery.readFractionBy π G.toFinset V Z < 1} := by + classical + rw [highMiss, average_eq_integral] + let S := {Z | Z ∈ highSet A i ∧ PoolQuery.readFractionBy π G.toFinset V Z < 1} + have hS : MeasurableSet S := (measurableSet_highSet A i).inter + (measurableSet_lt (PoolQuery.measurable_readFractionBy π G.toFinset V) measurable_const) + rw [← integral_indicator_one hS] + apply integral_congr_ae + filter_upwards [] with Z + have hf := finiteReads_eq_readFractionBy hi G hG V (testDepth A V) + (Nat.le_max_left _ _) Z + have hlt : finiteReads rules i G V (ScanRule.inputPrefix Z (testDepth A V)) < 1 ↔ + PoolQuery.readFractionBy π G.toFinset V Z < 1 := by + rw [← hf] + exact_mod_cast Iff.rfl + have ht := highTable_inputPrefix A i (testDepth A V) (Nat.le_max_right _ _) Z + have he : (highTable A i (ScanRule.inputPrefix Z (testDepth A V)) && + decide (finiteReads rules i G V (ScanRule.inputPrefix Z (testDepth A V)) < 1)) = true ↔ + Z ∈ S := by + simp only [Bool.and_eq_true, decide_eq_true_eq, ht, hlt] + rfl + by_cases hz : Z ∈ S + · simp [he.mpr hz, Set.indicator_of_mem hz] + · have hh := mt he.mp hz + simp [hh, Set.indicator_of_notMem hz] + +/-- Exact interpretation of one finite expected read fraction. -/ +theorem average_finiteReads_eq_integral {rules : List ScanRule} {i : ℕ} {π : ScanRule} + (hi : rules[i]? = some π) (A : Advice) (G : List ℕ) (hG : G.Nodup) (V : ℕ) : + (average (testDepth A V) (finiteReads rules i G V) : ℝ) = + ∫ Z, PoolQuery.readFractionBy π G.toFinset V Z ∂fairCoin := by + rw [average_eq_integral] + apply integral_congr_ae + exact Filter.Eventually.of_forall fun Z => + finiteReads_eq_readFractionBy hi G hG V (testDepth A V) (Nat.le_max_left _ _) Z + +/-- The weighted finite check integrates the actual scans supplied in the fixed list. -/ +theorem weightedMass_eq_sum_integral {rules : List ScanRule} (π : ℕ → ScanRule) + (hπ : ∀ i < rules.length, rules[i]? = some (π i)) + (A : Advice) (G : List ℕ) (hG : G.Nodup) (V : ℕ) : + (weightedMass rules A G V : ℝ) = + ∑ i ∈ Finset.range rules.length, + (weight i : ℝ) * ∫ Z, PoolQuery.readFractionBy (π i) G.toFinset V Z ∂fairCoin := by + unfold weightedMass + push_cast + rw [List.map_map, ← List.sum_toFinset _ (List.nodup_range (n := rules.length))] + simp only [List.toFinset_range, Function.comp_def] + apply Finset.sum_congr rfl + intro i hi + rw [Rat.cast_mul, average_finiteReads_eq_integral + (hπ i (Finset.mem_range.mp hi)) A G hG V] + +/-- Every accepted pair passes the three actual measure-theoretic tests. -/ +theorem Accepted.measure_spec {rules : List ScanRule} {A : Advice} {M : ℕ} + {C : Candidate} (h : Accepted rules A M C) (π : ℕ → ScanRule) + (hπ : ∀ i < rules.length, rules[i]? = some (π i)) + (hℓ : A.protectedCount ≤ rules.length) : + (∀ i < A.protectedCount, + fairCoin.real {Z | Z ∈ highSet A i ∧ + PoolQuery.readFractionBy (π i) C.1.toFinset C.2 Z < 1} < 3 * (A.error : ℝ)) ∧ + (∀ i < A.protectedCount, + (∫ Z, |PoolQuery.readFractionBy (π i) C.1.toFinset C.2 Z - approx A i Z| ∂fairCoin) < + 3 * (A.error : ℝ)) ∧ + (A.threshold : ℝ) < ∑ i ∈ Finset.range rules.length, + (weight i : ℝ) * ∫ Z, PoolQuery.readFractionBy (π i) C.1.toFinset C.2 Z ∂fairCoin := by + refine ⟨?_, ?_, ?_⟩ + · intro i hi + have ht := h.2.2.2.1 i hi + have hr : (highMiss rules A C.1 C.2 i : ℝ) < 3 * (A.error : ℝ) := by exact_mod_cast ht + rwa [highMiss_eq_measureReal (hπ i (hi.trans_le hℓ)) A C.1 h.2.1 C.2] at hr + · intro i hi + have ht := h.2.2.2.2.1 i hi + have hr : (distance rules A C.1 C.2 i : ℝ) < 3 * (A.error : ℝ) := by exact_mod_cast ht + rwa [distance_eq_integral (hπ i (hi.trans_le hℓ)) A C.1 h.2.1 C.2] at hr + · have ht : (A.threshold : ℝ) < (weightedMass rules A C.1 C.2 : ℝ) := by + exact_mod_cast h.2.2.2.2.2 + rwa [weightedMass_eq_sum_integral π hπ A C.1 h.2.1 C.2] at ht + +end Klr.PoolAdvice diff --git a/LeanPool/KLRandomness/PoolAdviceTables.lean b/LeanPool/KLRandomness/PoolAdviceTables.lean new file mode 100644 index 0000000000..221eda17d5 --- /dev/null +++ b/LeanPool/KLRandomness/PoolAdviceTables.lean @@ -0,0 +1,131 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.PoolAdvice +public import LeanPool.KLRandomness.PoolApproximationFunction + +/-! +# Ordinary finite encodings of prefix tables + +An arbitrary table on the finite type of depth-d binary prefixes has an +ordinary finite-list encoding for the pool checker. Thus choosing analytic +clopen and rational cylinder approximations only supplies finite advice; it +does not supply a membership oracle for an infinite set. +-/ + +@[expose] public section + +namespace Klr.PoolAdvice + +open MeasureTheory +open scoped symmDiff + +/-- Every function on depth-d binary words has a finite list representation, +using the same ordinary word encodings as the pool checker. -/ +theorem exists_list_table {β : Type*} (d : ℕ) (f : (Fin d → Bool) → β) (default : β) : + ∃ L : List β, ∀ u : Fin d → Bool, + L.getD (Encodable.encode (List.ofFn u)) default = f u := by + classical + let bound := (Finset.univ : Finset (Fin d → Bool)).sup + (fun u => Encodable.encode (List.ofFn u)) + 1 + let value (n : ℕ) : β := f (fun i => + ((@Encodable.decode (List Bool) inferInstance n).getD []).getD i.val false) + refine ⟨List.ofFn (fun n : Fin bound => value n.val), ?_⟩ + intro u + have hu : Encodable.encode (List.ofFn u) < bound := by + exact Nat.lt_succ_of_le (Finset.le_sup + (f := fun u : Fin d → Bool => Encodable.encode (List.ofFn u)) (Finset.mem_univ u)) + simp only [List.getD_eq_getElem?_getD, List.getElem?_ofFn, hu, ↓reduceDIte, + Option.getD_some] + change value (Encodable.encode (List.ofFn u)) = f u + dsimp only [value] + rw [Encodable.encodek] + congr 1 + funext i + simp [List.getD_eq_getElem?_getD, i.isLt] + +theorem inputPrefix_eq_ofFn (Z : Cantor) (d : ℕ) : + ScanRule.inputPrefix Z d = List.ofFn (PoolApproximation.bits d Z) := by + apply List.ext_getElem + · simp + · intro i hi hi' + simp only [ScanRule.inputPrefix, List.getElem_map, List.getElem_range, + List.getElem_ofFn, PoolApproximation.bits] + +/-- The list representation evaluates exactly to the original finite table +on every infinite sequence. -/ +theorem exists_list_prefix_table {β : Type*} (d : ℕ) + (f : (Fin d → Bool) → β) (default : β) : + ∃ L : List β, ∀ Z : Cantor, + L.getD (Encodable.encode (ScanRule.inputPrefix Z d)) default = + PoolApproximation.eval f Z := by + obtain ⟨L, hL⟩ := exists_list_table d f default + refine ⟨L, fun Z => ?_⟩ + rw [inputPrefix_eq_ofFn] + exact hL (PoolApproximation.bits d Z) + +/-- All the finitely many clopen and rational tables can be encoded together +in one finite list, with a single common depth. -/ +theorem exists_advice_tables (d D : ℕ) + (H : Fin D → (Fin d → Bool) → Bool) (ψ : Fin D → (Fin d → Bool) → ℚ) : + ∃ tables : List Table, ∀ i : Fin D, ∀ Z : Cantor, + ((tables.getD i.val ([], [])).1).getD + (Encodable.encode (ScanRule.inputPrefix Z d)) false = PoolApproximation.eval (H i) Z ∧ + ((tables.getD i.val ([], [])).2).getD + (Encodable.encode (ScanRule.inputPrefix Z d)) 0 = PoolApproximation.eval (ψ i) Z := by + classical + choose LH hH using fun i => exists_list_prefix_table d (H i) false + choose Lψ hψ using fun i => exists_list_prefix_table d (ψ i) 0 + refine ⟨List.ofFn (fun i : Fin D => (LH i, Lψ i)), ?_⟩ + intro i Z + simp only [List.getD_eq_getElem?_getD, List.getElem?_ofFn, i.isLt, ↓reduceDIte, + Option.getD_some] + exact ⟨hH i Z, hψ i Z⟩ + +/-- A finite family of Borel high sets and bounded measurable limit functions +admits one fixed finite advice record, with no dependence on a future pool size. -/ +theorem exists_approximating_advice (D z ℓ : ℕ) (δ γ : ℚ) (hδ : 0 < δ) + (H : Fin D → Set Cantor) (hH : ∀ i, MeasurableSet (H i)) + (g : Fin D → Cantor → ℝ) (hgm : ∀ i, Measurable (g i)) + (hg0 : ∀ i Z, 0 ≤ g i Z) (hg1 : ∀ i Z, g i Z ≤ 1) : + ∃ A : Advice, A.positionBound = z ∧ A.protectedCount = ℓ ∧ + A.error = δ ∧ A.threshold = γ ∧ ∀ i : Fin D, + fairCoin.real (highSet A i.val ∆ H i) < (δ : ℝ) ∧ + (∀ Z, 0 ≤ approx A i.val Z ∧ approx A i.val Z ≤ 1) ∧ + (∫ Z, |approx A i.val Z - g i Z| ∂fairCoin) < (δ : ℝ) := by + classical + have hδr : (0 : ℝ) < δ := by exact_mod_cast hδ + obtain ⟨d, high, value, happrox⟩ := + PoolApproximation.exists_common_tables H hH g hgm hg0 hg1 hδr hδr + obtain ⟨tables, htables⟩ := exists_advice_tables d D high value + let A : Advice := ⟨z, ℓ, d, δ, γ, tables⟩ + have htake (Z : Cantor) : (ScanRule.inputPrefix Z d).take d = + ScanRule.inputPrefix Z d := List.take_of_length_le (by simp) + have hhigh (i : Fin D) : highSet A i.val = PoolApproximation.event (high i) := by + ext Z + change (((tables.getD i.val ([], [])).1).getD + (Encodable.encode ((ScanRule.inputPrefix Z d).take d)) false = true) ↔ _ + rw [htake Z, (htables i Z).1] + rfl + have hvalue (i : Fin D) (Z : Cantor) : approx A i.val Z = + ((PoolApproximation.eval (value i) Z : ℚ) : ℝ) := by + change ((((tables.getD i.val ([], [])).2).getD + (Encodable.encode ((ScanRule.inputPrefix Z d).take d)) 0 : ℚ) : ℝ) = _ + rw [htake Z, (htables i Z).2] + refine ⟨A, rfl, rfl, rfl, rfl, fun i => ⟨?_, ?_, ?_⟩⟩ + · rw [hhigh i] + exact (happrox i).1 + · intro Z + rw [hvalue] + exact_mod_cast (happrox i).2.1 (PoolApproximation.bits d Z) + · simp_rw [hvalue] + simpa only [Real.norm_eq_abs] using (happrox i).2.2 + +end Klr.PoolAdvice diff --git a/LeanPool/KLRandomness/PoolApproximation.lean b/LeanPool/KLRandomness/PoolApproximation.lean new file mode 100644 index 0000000000..cbcb1897be --- /dev/null +++ b/LeanPool/KLRandomness/PoolApproximation.lean @@ -0,0 +1,140 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.NoDrop +public import Mathlib.MeasureTheory.Measure.MeasuredSets + +/-! +# Finite-prefix approximation of Borel events + +Every Borel event in Cantor space can be approximated in fair-coin measure by +a Boolean table on a fixed finite prefix. The depth and the table are chosen +once, independently of any later affine block. +-/ + +@[expose] public section + +namespace Klr.PoolApproximation + +open MeasureTheory +open scoped ENNReal symmDiff + +/-- The first `d` bits, viewed as a member of a finite type. -/ +def bits (d : ℕ) (X : Cantor) : Fin d → Bool := fun i => X i.val + +/-- Evaluate a finite table on an input sequence. -/ +def eval {E : Type*} {d : ℕ} (table : (Fin d → Bool) → E) (X : Cantor) : E := + table (bits d X) + +/-- A finite Boolean table describes a finite union of prefix cylinders. -/ +def event {d : ℕ} (table : (Fin d → Bool) → Bool) : Set Cantor := + {X | eval table X = true} + +/-- Read a shallower table from a longer prefix. -/ +def liftTable {E : Type*} {d e : ℕ} (h : d ≤ e) + (table : (Fin d → Bool) → E) : (Fin e → Bool) → E := + fun u => table (fun i => u (Fin.castLE h i)) + +@[simp] theorem eval_liftTable {E : Type*} {d e : ℕ} (h : d ≤ e) + (table : (Fin d → Bool) → E) (X : Cantor) : + eval (liftTable h table) X = eval table X := rfl + +@[simp] theorem event_liftTable {d e : ℕ} (h : d ≤ e) + (table : (Fin d → Bool) → Bool) : event (liftTable h table) = event table := rfl + +theorem measurable_prefix (d : ℕ) : Measurable (bits d) := + Measurable.of_eval fun i => measurable_pi_apply i.val + +theorem measurable_eval {E : Type*} [MeasurableSpace E] {d : ℕ} + (table : (Fin d → Bool) → E) : Measurable (eval table) := + (measurable_of_finite table).comp (measurable_prefix d) + +theorem measurableSet_event {d : ℕ} (table : (Fin d → Bool) → Bool) : + MeasurableSet (event table) := + (measurable_eval table) (measurableSet_singleton true) + +/-- The algebra of events determined by a finite initial segment. -/ +def prefixEvents : Set (Set Cantor) := + {s | ∃ (d : ℕ) (table : (Fin d → Bool) → Bool), s = event table} + +theorem empty_mem_prefixEvents : ∅ ∈ prefixEvents := by + refine ⟨0, fun _ => false, ?_⟩ + ext X + simp [event, eval] + +theorem univ_mem_prefixEvents : Set.univ ∈ prefixEvents := by + refine ⟨0, fun _ => true, ?_⟩ + ext X + simp [event, eval] + +theorem isSetRing_prefixEvents : IsSetRing prefixEvents where + empty_mem := empty_mem_prefixEvents + union_mem := by + rintro s t ⟨d, a, rfl⟩ ⟨e, b, rfl⟩ + refine ⟨max d e, fun u => + liftTable (Nat.le_max_left d e) a u || liftTable (Nat.le_max_right d e) b u, ?_⟩ + ext X + change (a (bits d X) = true ∨ b (bits e X) = true) ↔ + (a (bits d X) || b (bits e X)) = true + simp + sdiff_mem := by + rintro s t ⟨d, a, rfl⟩ ⟨e, b, rfl⟩ + refine ⟨max d e, fun u => + liftTable (Nat.le_max_left d e) a u && !(liftTable (Nat.le_max_right d e) b u), ?_⟩ + ext X + change (a (bits d X) = true ∧ ¬ b (bits e X) = true) ↔ + (a (bits d X) && !(b (bits e X))) = true + simp + +theorem cylinder_mem_prefixEvents (s : List Bool) : cylinder s ∈ prefixEvents := by + classical + refine ⟨s.length, fun u => decide (∀ i : Fin s.length, u i = s.getD i.val false), ?_⟩ + ext X + change (∀ i < s.length, X i = s.getD i false) ↔ + decide (∀ i : Fin s.length, X i.val = s.getD i.val false) = true + exact ⟨fun h => decide_eq_true (fun i => h i.val i.isLt), + fun h i hi => of_decide_eq_true h ⟨i, hi⟩⟩ + +theorem measurableSpace_eq_generateFrom_prefixEvents : + (inferInstance : MeasurableSpace Cantor) = + MeasurableSpace.generateFrom prefixEvents := by + apply le_antisymm + · rw [measurableSpace_eq_generateFrom_cylinders] + apply MeasurableSpace.generateFrom_mono + rintro _ ⟨s, rfl⟩ + exact cylinder_mem_prefixEvents s + · apply MeasurableSpace.generateFrom_le + rintro _ ⟨d, table, rfl⟩ + exact measurableSet_event table + +/-- A Borel event admits a finite Boolean prefix approximation with any positive error. -/ +theorem exists_event_symmDiff_lt {H : Set Cantor} (hH : MeasurableSet H) + {ε : ℝ≥0∞} (hε : 0 < ε) : + ∃ (d : ℕ) (table : (Fin d → Bool) → Bool), fairCoin (event table ∆ H) < ε := by + have hcover : ∃ D : Set (Set Cantor), + D.Countable ∧ D ⊆ prefixEvents ∧ fairCoin (⋃₀ D)ᶜ = 0 := by + refine ⟨{Set.univ}, Set.countable_singleton _, ?_, ?_⟩ + · simpa using univ_mem_prefixEvents + · simp + obtain ⟨s, ⟨d, table, rfl⟩, hs⟩ := + exists_measure_symmDiff_lt_of_generateFrom_isSetRing isSetRing_prefixEvents hcover + measurableSpace_eq_generateFrom_prefixEvents hH hε + exact ⟨d, table, hs⟩ + +/-- The same approximation with a real-valued error bound. -/ +theorem exists_event_measureReal_symmDiff_lt {H : Set Cantor} (hH : MeasurableSet H) + {ε : ℝ} (hε : 0 < ε) : + ∃ (d : ℕ) (table : (Fin d → Bool) → Bool), fairCoin.real (event table ∆ H) < ε := by + obtain ⟨d, table, ht⟩ := exists_event_symmDiff_lt hH (ENNReal.ofReal_pos.mpr hε) + refine ⟨d, table, ?_⟩ + exact (ENNReal.toReal_lt_toReal (measure_ne_top _ _) ENNReal.ofReal_ne_top).mpr ht |>.trans_eq + (ENNReal.toReal_ofReal hε.le) + +end Klr.PoolApproximation diff --git a/LeanPool/KLRandomness/PoolApproximationFunction.lean b/LeanPool/KLRandomness/PoolApproximationFunction.lean new file mode 100644 index 0000000000..42e60c3716 --- /dev/null +++ b/LeanPool/KLRandomness/PoolApproximationFunction.lean @@ -0,0 +1,245 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.PoolApproximation +public import Mathlib.MeasureTheory.Integral.Bochner.Set +public import Mathlib.MeasureTheory.Integral.Bochner.Basic +import Mathlib.Tactic.GCongr +import Mathlib.Tactic.Linarith +import Mathlib.Tactic.NormNum +import Mathlib.Tactic.Positivity +import Mathlib.Tactic.Ring + +/-! +# Finite-prefix approximation in L1 + +Real integrable functions on Cantor space are approximated in L1 by finite +tables. Rational tables suffice, and the approximants can stay in `[0,1]` +when the target function has that range. +-/ + +@[expose] public section + +namespace Klr.PoolApproximation + +open MeasureTheory Filter +open scoped ENNReal symmDiff Topology + +theorem integrable_eval {d : ℕ} (table : (Fin d → Bool) → ℝ) : + Integrable (eval table) fairCoin := by + exact (Integrable.of_finite (μ := Measure.map (bits d) fairCoin) (f := table)).comp_measurable + (measurable_prefix d) + +/-- The L1 error obeys the triangle inequality. -/ +theorem integral_norm_sub_triangle {f g h : Cantor → ℝ} + (hf : Integrable f fairCoin) (hg : Integrable g fairCoin) (hh : Integrable h fairCoin) : + (∫ X, ‖f X - h X‖ ∂fairCoin) ≤ + (∫ X, ‖f X - g X‖ ∂fairCoin) + ∫ X, ‖g X - h X‖ ∂fairCoin := by + calc + _ ≤ ∫ X, ‖f X - g X‖ + ‖g X - h X‖ ∂fairCoin := by + apply integral_mono (hf.sub hh).norm ((hf.sub hg).norm.add (hg.sub hh).norm) + intro X + simpa only [Pi.sub_apply, Pi.add_apply, dist_eq_norm] using dist_triangle (f X) (g X) (h X) + _ = _ := integral_add (hf.sub hg).norm (hg.sub hh).norm + +/-- Indicator error is precisely the measure of the symmetric difference, +multiplied by the size of the coefficient. -/ +theorem integral_norm_indicator_sub_indicator {s t : Set Cantor} + (hs : MeasurableSet s) (ht : MeasurableSet t) (c : ℝ) : + (∫ X, ‖s.indicator (fun _ => c) X - t.indicator (fun _ => c) X‖ ∂fairCoin) = + fairCoin.real (s ∆ t) * ‖c‖ := by + classical + calc + _ = ∫ X, (s ∆ t).indicator (fun _ => ‖c‖) X ∂fairCoin := by + apply integral_congr_ae + filter_upwards with X + by_cases hXs : X ∈ s <;> by_cases hXt : X ∈ t <;> + simp [Set.indicator, Set.mem_symmDiff, hXs, hXt] + _ = _ := by simpa using integral_indicator_const (μ := fairCoin) ‖c‖ (hs.symmDiff ht) + +/-- A scalar indicator can be approximated by a real prefix table. -/ +theorem exists_realTable_indicator {H : Set Cantor} (hH : MeasurableSet H) (c : ℝ) + {ε : ℝ} (hε : 0 < ε) : + ∃ (d : ℕ) (table : (Fin d → Bool) → ℝ), + (∫ X, ‖eval table X - H.indicator (fun _ => c) X‖ ∂fairCoin) < ε := by + classical + obtain ⟨d, table, ht⟩ := exists_event_measureReal_symmDiff_lt hH + (show 0 < ε / (‖c‖ + 1) by positivity) + refine ⟨d, fun u => if table u then c else 0, ?_⟩ + have he : eval (fun u => if table u then c else 0) = + (event table).indicator (fun _ => c) := by + funext X + simp only [eval, event, Set.indicator, Set.mem_ofPred] + rw [he, integral_norm_indicator_sub_indicator (measurableSet_event table) hH] + calc + _ ≤ fairCoin.real (event table ∆ H) * (‖c‖ + 1) := by + gcongr + linarith + _ < (ε / (‖c‖ + 1)) * (‖c‖ + 1) := + mul_lt_mul_of_pos_right ht (by positivity) + _ = ε := div_mul_cancel₀ ε (by positivity) + +/-- Every measurable simple real function admits finite-prefix L1 approximations. -/ +theorem exists_realTable_simpleFunc (f : SimpleFunc Cantor ℝ) : + ∀ (ε : ℝ), 0 < ε → ∃ (d : ℕ) (table : (Fin d → Bool) → ℝ), + (∫ X, ‖eval table X - f X‖ ∂fairCoin) < ε := by + classical + induction f using SimpleFunc.induction with + | const c hH => + intro ε hε + simpa only [SimpleFunc.piecewise_apply, SimpleFunc.const_apply, Set.indicator] using + exists_realTable_indicator hH c hε + | @add f g _ hf hg => + intro ε hε + obtain ⟨d, a, ha⟩ := hf (ε / 2) (half_pos hε) + obtain ⟨e, b, hb⟩ := hg (ε / 2) (half_pos hε) + let table : (Fin (max d e) → Bool) → ℝ := fun u => + liftTable (Nat.le_max_left d e) a u + liftTable (Nat.le_max_right d e) b u + refine ⟨max d e, table, ?_⟩ + have hpoint (X : Cantor) : + ‖eval table X - (f + g) X‖ ≤ ‖eval a X - f X‖ + ‖eval b X - g X‖ := by + have he : eval table X - (f + g) X = + (eval a X - f X) + (eval b X - g X) := by + change (eval a X + eval b X) - (f X + g X) = _ + ring + rw [he] + exact norm_add_le _ _ + calc + _ ≤ ∫ X, ‖eval a X - f X‖ + ‖eval b X - g X‖ ∂fairCoin := by + exact integral_mono + ((integrable_eval table).sub (f + g).integrable_of_isFiniteMeasure).norm + (((integrable_eval a).sub f.integrable_of_isFiniteMeasure).norm.add + ((integrable_eval b).sub g.integrable_of_isFiniteMeasure).norm) hpoint + _ = (∫ X, ‖eval a X - f X‖ ∂fairCoin) + ∫ X, ‖eval b X - g X‖ ∂fairCoin := + integral_add ((integrable_eval a).sub f.integrable_of_isFiniteMeasure).norm + ((integrable_eval b).sub g.integrable_of_isFiniteMeasure).norm + _ < ε := by linarith + +/-- Finite real prefix tables are dense in the real integrable functions. -/ +theorem exists_realTable_integral_norm_sub_lt {f : Cantor → ℝ} + (hfm : Measurable f) (hf : Integrable f fairCoin) {ε : ℝ} (hε : 0 < ε) : + ∃ (d : ℕ) (table : (Fin d → Bool) → ℝ), + (∫ X, ‖eval table X - f X‖ ∂fairCoin) < ε := by + obtain ⟨n, hn⟩ := ((tendsto_integral_norm_approxOn_sub hfm hf).eventually + (gt_mem_nhds (half_pos hε))).exists + let g : SimpleFunc Cantor ℝ := SimpleFunc.approxOn f hfm (Set.range f ∪ {0}) 0 (by simp) n + obtain ⟨d, table, ht⟩ := exists_realTable_simpleFunc g (ε / 2) (half_pos hε) + refine ⟨d, table, ?_⟩ + have htriangle := integral_norm_sub_triangle (integrable_eval table) + g.integrable_of_isFiniteMeasure hf + have hgn : (∫ X, ‖g X - f X‖ ∂fairCoin) < ε / 2 := hn + linarith + +/-- A finite real table has a uniformly close rational table. -/ +theorem exists_ratTable_uniform_lt {d : ℕ} (table : (Fin d → Bool) → ℝ) + {ε : ℝ} (hε : 0 < ε) : + ∃ q : (Fin d → Bool) → ℚ, ∀ u, ‖(q u : ℝ) - table u‖ < ε := by + have h (u : Fin d → Bool) : ∃ q : ℚ, ‖(q : ℝ) - table u‖ < ε := by + obtain ⟨q, hlo, hhi⟩ := exists_rat_btwn + (show table u - ε < table u + ε by linarith) + refine ⟨q, ?_⟩ + rw [Real.norm_eq_abs, abs_lt] + constructor <;> linarith + choose q hq using h + exact ⟨q, hq⟩ + +/-- Rational-valued finite tables are dense in L1 on fair-coin Cantor space. -/ +theorem exists_ratTable_integral_norm_sub_lt {f : Cantor → ℝ} + (hfm : Measurable f) (hf : Integrable f fairCoin) {ε : ℝ} (hε : 0 < ε) : + ∃ (d : ℕ) (table : (Fin d → Bool) → ℚ), + (∫ X, ‖((eval table X : ℚ) : ℝ) - f X‖ ∂fairCoin) < ε := by + obtain ⟨d, table, ht⟩ := exists_realTable_integral_norm_sub_lt hfm hf (half_pos hε) + obtain ⟨q, hq⟩ := exists_ratTable_uniform_lt table (half_pos hε) + have hiq := integrable_eval (fun u => (q u : ℝ)) + have hqint : (∫ X, ‖((eval q X : ℚ) : ℝ) - eval table X‖ ∂fairCoin) ≤ ε / 2 := by + calc + _ ≤ ∫ _ : Cantor, ε / 2 ∂fairCoin := by + apply integral_mono (hiq.sub (integrable_eval table)).norm (integrable_const _) + intro X + exact (hq (bits d X)).le + _ = ε / 2 := by simp + refine ⟨d, q, ?_⟩ + have htriangle := integral_norm_sub_triangle hiq (integrable_eval table) hf + simp only [eval] at htriangle hqint ht ⊢ + linarith + +/-- Clipping to the unit interval cannot increase error against a point in that interval. -/ +theorem norm_clip_sub_le (a b : ℝ) (hb0 : 0 ≤ b) (hb1 : b ≤ 1) : + ‖min 1 (max 0 a) - b‖ ≤ ‖a - b‖ := by + rw [Real.norm_eq_abs, Real.norm_eq_abs] + by_cases ha0 : a ≤ 0 + · rw [max_eq_left ha0, min_eq_right (by norm_num : (0 : ℝ) ≤ 1), zero_sub, abs_neg, + abs_of_nonneg hb0, abs_of_nonpos (by linarith : a - b ≤ 0)] + linarith + · rw [max_eq_right (le_of_lt (lt_of_not_ge ha0))] + by_cases ha1 : 1 ≤ a + · rw [min_eq_left ha1, abs_of_nonneg (by linarith : 0 ≤ 1 - b), + abs_of_nonneg (by linarith : 0 ≤ a - b)] + linarith + · rw [min_eq_right (le_of_lt (lt_of_not_ge ha1))] + +/-- A measurable `[0,1]`-valued target admits a fixed rational prefix table, +also valued in `[0,1]`, with arbitrarily small L1 error. -/ +theorem exists_unitRatTable_integral_norm_sub_lt {f : Cantor → ℝ} + (hfm : Measurable f) (hf0 : ∀ X, 0 ≤ f X) (hf1 : ∀ X, f X ≤ 1) + {ε : ℝ} (hε : 0 < ε) : + ∃ (d : ℕ) (table : (Fin d → Bool) → ℚ), + (∀ u, 0 ≤ table u ∧ table u ≤ 1) ∧ + (∫ X, ‖((eval table X : ℚ) : ℝ) - f X‖ ∂fairCoin) < ε := by + have hf : Integrable f fairCoin := Integrable.of_bound hfm.aestronglyMeasurable 1 + (Filter.Eventually.of_forall fun X => by + rw [Real.norm_eq_abs, abs_of_nonneg (hf0 X)] + exact hf1 X) + obtain ⟨d, table, ht⟩ := exists_ratTable_integral_norm_sub_lt hfm hf hε + let q : (Fin d → Bool) → ℚ := fun u => min 1 (max 0 (table u)) + refine ⟨d, q, ?_, ?_⟩ + · intro u + exact ⟨le_min (by norm_num) (le_max_left _ _), min_le_left _ _⟩ + · calc + _ ≤ ∫ X, ‖((eval table X : ℚ) : ℝ) - f X‖ ∂fairCoin := by + apply integral_mono ((integrable_eval (fun u => (q u : ℝ))).sub hf).norm + ((integrable_eval (fun u => (table u : ℝ))).sub hf).norm + intro X + simpa only [eval, q, Rat.cast_min, Rat.cast_max, Rat.cast_one, Rat.cast_zero, + Pi.sub_apply] using norm_clip_sub_le ((eval table X : ℚ) : ℝ) (f X) (hf0 X) (hf1 X) + _ < ε := ht + +/-- A finite family of Borel events and unit-interval functions has simultaneous +approximations at one common depth. All the tables are fixed before a later +affine block or its dimension is selected. -/ +theorem exists_common_tables {ι : Type*} [Finite ι] + (H : ι → Set Cantor) (hH : ∀ i, MeasurableSet (H i)) + (f : ι → Cantor → ℝ) (hfm : ∀ i, Measurable (f i)) + (hf0 : ∀ i X, 0 ≤ f i X) (hf1 : ∀ i X, f i X ≤ 1) + {εH εf : ℝ} (hεH : 0 < εH) (hεf : 0 < εf) : + ∃ (d : ℕ) (high : ι → (Fin d → Bool) → Bool) (value : ι → (Fin d → Bool) → ℚ), + ∀ i, fairCoin.real (event (high i) ∆ H i) < εH ∧ + (∀ u, 0 ≤ value i u ∧ value i u ≤ 1) ∧ + (∫ X, ‖((eval (value i) X : ℚ) : ℝ) - f i X‖ ∂fairCoin) < εf := by + classical + let : Fintype ι := Fintype.ofFinite ι + choose dH high hhigh using fun i => exists_event_measureReal_symmDiff_lt (hH i) hεH + choose df value hvalue herror using fun i => + exists_unitRatTable_integral_norm_sub_lt (hfm i) (hf0 i) (hf1 i) hεf + let d := max (Finset.univ.sup dH) (Finset.univ.sup df) + have hHd (i : ι) : dH i ≤ d := + (Finset.le_sup (f := dH) (Finset.mem_univ i)).trans (Nat.le_max_left _ _) + have hfd (i : ι) : df i ≤ d := + (Finset.le_sup (f := df) (Finset.mem_univ i)).trans (Nat.le_max_right _ _) + refine ⟨d, fun i => liftTable (hHd i) (high i), + fun i => liftTable (hfd i) (value i), ?_⟩ + intro i + refine ⟨?_, ?_, ?_⟩ + · simpa only [event_liftTable] using hhigh i + · intro u + exact hvalue i (fun j => u (Fin.castLE (hfd i) j)) + · simpa only [eval_liftTable] using herror i + +end Klr.PoolApproximation diff --git a/LeanPool/KLRandomness/PoolConstruction.lean b/LeanPool/KLRandomness/PoolConstruction.lean new file mode 100644 index 0000000000..8a58eeb115 --- /dev/null +++ b/LeanPool/KLRandomness/PoolConstruction.lean @@ -0,0 +1,129 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.PoolAcceptance +public import LeanPool.KLRandomness.PoolParameters +public import LeanPool.KLRandomness.PoolCoverage + +/-! +# The computable pool lemma with fixed Borel partitions + +For every countable family of total computable scans, one Borel partition per +scan can be fixed before all finite-stage parameters. For any protected +prefix, positive error tolerance and position cutoff, a positive rational +margin and one ordinary partial-recursive program are then fixed. That +program, given only the requested pool size, halts at every sufficiently large +size and returns a pool satisfying both of the paper's missed-position bounds. + +The final theorem discharges weak-limit existence, finite advice, termination, +and soundness. None of them is a hypothesis of the pool lemma. +-/ + +@[expose] public section + +namespace Klr.PoolConstruction + +open Filter MeasureTheory PoolAdvice +open scoped Topology BigOperators symmDiff + +/-- The paper's two pool bounds, stated with actual missed positions and their +cardinality. The high/low partition is represented by a set and its complement. -/ +def GoodPool (π : ℕ → ScanRule) (H : ℕ → Set Cantor) (ℓ : ℕ) (η : ℝ) + (z : ℕ) (τ : ℚ) (M : ℕ) (G : List ℕ) : Prop := + G.length = M ∧ G.Nodup ∧ (∀ b ∈ G, z ≤ b) ∧ + ∀ i < ℓ, + fairCoin.real {Z | Z ∈ H i ∧ ∃ b ∈ G, ¬ PoolQuery.Reads (π i) b Z} < η ∧ + fairCoin.real {Z | Z ∈ (H i)ᶜ ∧ + (PoolQuery.missedCount (π i) G.toFinset Z : ℝ) < (τ : ℝ) * M} < η + +namespace FixedParameters + +variable {π : ℕ → ScanRule} {a : ℕ → ℕ} {Q : Pool.QueryPartition π a} + {ℓ : ℕ} {η : ℝ} {z : ℕ} (P : PoolAdvice.FixedParameters Q ℓ η z) + +/-- Soundness in the paper's exact missed-position formulation holds for every +accepted output, not only for the pools used to prove termination. -/ +theorem goodPool_of_accepted {M : ℕ} {C : Candidate} + (h : Accepted P.rules P.advice M C) : + GoodPool π Q.high ℓ η z P.margin M C.1 := by + refine ⟨h.1, h.2.1, fun b hb => P.position_ge.trans (h.2.2.1 b hb), ?_⟩ + intro i hi + have hbounds := P.accepted_measure_bounds h i hi + refine ⟨?_, ?_⟩ + · apply lt_of_le_of_lt (measureReal_mono (μ := fairCoin) ?_) hbounds.1 + intro Z hZ + refine ⟨hZ.1, PoolQuery.readFraction_lt_one_of_exists_missed (π i) Z ?_⟩ + obtain ⟨b, hb, hmiss⟩ := hZ.2 + exact ⟨b, List.mem_toFinset.mpr hb, hmiss⟩ + · apply lt_of_le_of_lt (measureReal_mono (μ := fairCoin) ?_) hbounds.2 + intro Z hZ + refine ⟨hZ.1, PoolQuery.one_sub_lt_readFraction_of_missedCount_lt + (π i) C.1.toFinset Z (P.margin : ℝ) ?_⟩ + rw [List.toFinset_card_of_nodup h.2.1, h.1] + exact hZ.2 + +/-- Every value of the actual pool-producing partial function satisfies the +two measure bounds and the requested finite combinatorial conditions. -/ +theorem goodPool_of_mem {M : ℕ} {G : List ℕ} + (hG : G ∈ pool P.rules P.advice M) : + GoodPool π Q.high ℓ η z P.margin M G := by + obtain ⟨V, hV⟩ := pool_spec hG + exact goodPool_of_accepted P hV + +/-- The analytic witness and finite-horizon convergence prove eventual +termination for the chosen fixed advice. -/ +theorem eventually_accepted + (ha : Tendsto Q.position atTop atTop) + (hp : Tendsto (Pool.weightedQueryProbability π ∘ Q.position) atTop + (𝓝 (Pool.weightedQueryLimsup π))) : + ∀ᶠ M : ℕ in atTop, ∃ C, Accepted P.rules P.advice M C := by + apply Q.eventually_exists_accepted ha P.rules ?_ P.advice P.protected_le_length + P.error_real_pos ?_ ?_ (P.eventually_weighted_above hp) + · intro i hi + exact P.getElem?_rules (by simpa only [P.length_rules] using hi) + · intro i hi + exact P.high_approx i (by rwa [P.protected_eq] at hi) + · intro i hi + exact P.function_approx i (by rwa [P.protected_eq] at hi) + +/-- One fixed program returns good pools at all sufficiently large sizes. -/ +theorem exists_eventual_goodPool_program + (ha : Tendsto Q.position atTop atTop) + (hp : Tendsto (Pool.weightedQueryProbability π ∘ Q.position) atTop + (𝓝 (Pool.weightedQueryLimsup π))) : + ∃ e : Nat.Partrec.Code, ∀ᶠ M : ℕ in atTop, + ∃ G : List ℕ, encodePool G ∈ e.eval M ∧ GoodPool π Q.high ℓ η z P.margin M G := by + obtain ⟨e, he⟩ := exists_eventual_pool_program P.rules P.advice (eventually_accepted P ha hp) + refine ⟨e, ?_⟩ + filter_upwards [he] with M hM + obtain ⟨G, V, hcode, haccepted⟩ := hM + exact ⟨G, hcode, goodPool_of_accepted P haccepted⟩ + +end FixedParameters + +/-- Lemma 3: fixed Borel partitions and fixed-advice computable pools. + +The order of quantifiers is essential. The sets `H` precede `ℓ`, `η` and `z`; +the rational margin and the program precede the varying input `M`. Only the +program's running time and its output pool depend on that input. -/ +theorem exists_fixed_partitions_computable_pools (π : ℕ → ScanRule) : + ∃ H : ℕ → Set Cantor, (∀ i, MeasurableSet (H i)) ∧ + ∀ (ℓ : ℕ) (η : ℝ), 0 < η → ∀ z : ℕ, + ∃ τ : ℚ, 0 < τ ∧ τ < 1 / 4 ∧ + ∃ e : Nat.Partrec.Code, ∀ᶠ M : ℕ in atTop, + ∃ G : List ℕ, encodePool G ∈ e.eval M ∧ GoodPool π H ℓ η z τ M G := by + obtain ⟨a, Q, ha, hp, _⟩ := Pool.exists_weighted_queryPartition π + refine ⟨Q.high, Q.measurableSet_high, ?_⟩ + intro ℓ η hη z + obtain ⟨P⟩ := exists_fixedParameters Q ℓ hη z + exact ⟨P.margin, P.margin_pos, P.margin_lt_quarter, + FixedParameters.exists_eventual_goodPool_program P ha hp⟩ + +end Klr.PoolConstruction diff --git a/LeanPool/KLRandomness/PoolCoverage.lean b/LeanPool/KLRandomness/PoolCoverage.lean new file mode 100644 index 0000000000..d7bb8bca5c --- /dev/null +++ b/LeanPool/KLRandomness/PoolCoverage.lean @@ -0,0 +1,132 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.PoolQuery +import Mathlib.Tactic.Linarith + +/-! +# Query fractions and exact missed-position counts + +The analytic pool estimates use the fraction of a finite pool read by a scan. +The paper states the conclusion using missed positions. For a nonempty finite +pool these formulations agree exactly, including the strict inequality in +"fewer than `τ * M` missed positions". +-/ + +@[expose] public section + +noncomputable section + +namespace Klr.PoolQuery + +open Set +open scoped BigOperators + +/-- The number of positions in the pool never queried on the prescribed answer +sequence. -/ +def missedCount (π : ScanRule) (G : Finset ℕ) (Z : Cantor) : ℕ := by + classical + exact (G.filter fun a => ¬ Reads π a Z).card + +theorem missedCount_le_card (π : ScanRule) (G : Finset ℕ) (Z : Cantor) : + missedCount π G Z ≤ G.card := by + classical + exact Finset.card_filter_le _ _ + +open Classical in +theorem sum_indicator_eq_readCount (π : ScanRule) (G : Finset ℕ) (Z : Cantor) : + (∑ a ∈ G, indicator π a Z) = ((G.filter fun a => Reads π a Z).card : ℝ) := by + classical + simp [indicator, Set.indicator_apply] + +theorem sum_indicator_add_missedCount (π : ScanRule) (G : Finset ℕ) (Z : Cantor) : + (∑ a ∈ G, indicator π a Z) + (missedCount π G Z : ℝ) = G.card := by + classical + rw [sum_indicator_eq_readCount] + exact_mod_cast (Finset.card_filter_add_card_filter_not (s := G) (fun a => Reads π a Z)) + +theorem sum_indicator_eq_card_sub_missedCount (π : ScanRule) (G : Finset ℕ) (Z : Cantor) : + (∑ a ∈ G, indicator π a Z) = (G.card : ℝ) - missedCount π G Z := by + have h := sum_indicator_add_missedCount π G Z + linarith + +/-- The exact numerical identity relating read fraction and missed count. -/ +theorem readFraction_eq_one_sub_missedCount (π : ScanRule) {G : Finset ℕ} + (hG : G.Nonempty) (Z : Cantor) : + readFraction π G Z = 1 - (missedCount π G Z : ℝ) / G.card := by + have hcard : (G.card : ℝ) ≠ 0 := by exact_mod_cast (Nat.ne_of_gt hG.card_pos) + rw [readFraction, sum_indicator_eq_card_sub_missedCount, sub_div, div_self hcard] + +theorem missedCount_pos_iff (π : ScanRule) (G : Finset ℕ) (Z : Cantor) : + 0 < missedCount π G Z ↔ ∃ a ∈ G, ¬ Reads π a Z := by + classical + simp [missedCount, Finset.card_pos, Finset.filter_nonempty_iff] + +theorem missedCount_eq_zero_iff (π : ScanRule) (G : Finset ℕ) (Z : Cantor) : + missedCount π G Z = 0 ↔ ∀ a ∈ G, Reads π a Z := by + classical + simp [missedCount, Finset.filter_eq_empty_iff] + +theorem readFraction_lt_one_iff_missedCount_pos (π : ScanRule) {G : Finset ℕ} + (hG : G.Nonempty) (Z : Cantor) : + readFraction π G Z < 1 ↔ 0 < missedCount π G Z := by + have hcard : 0 < (G.card : ℝ) := by exact_mod_cast hG.card_pos + rw [readFraction_eq_one_sub_missedCount π hG, sub_lt_self_iff, + div_pos_iff_of_pos_right hcard, Nat.cast_pos] + +/-- Failure to read the whole nonempty pool means that at least one pool +position is missed. -/ +theorem readFraction_lt_one_iff_exists_missed (π : ScanRule) {G : Finset ℕ} + (hG : G.Nonempty) (Z : Cantor) : + readFraction π G Z < 1 ↔ ∃ a ∈ G, ¬ Reads π a Z := + (readFraction_lt_one_iff_missedCount_pos π hG Z).trans (missedCount_pos_iff π G Z) + +/-- The paper's strict missed-count inequality is exactly the strict +near-full-coverage inequality. No rounding of the real threshold occurs. -/ +theorem one_sub_lt_readFraction_iff_missedCount_lt (π : ScanRule) {G : Finset ℕ} + (hG : G.Nonempty) (Z : Cantor) (τ : ℝ) : + 1 - τ < readFraction π G Z ↔ (missedCount π G Z : ℝ) < τ * G.card := by + have hcard : 0 < (G.card : ℝ) := by exact_mod_cast hG.card_pos + rw [readFraction_eq_one_sub_missedCount π hG] + calc + 1 - τ < 1 - (missedCount π G Z : ℝ) / G.card ↔ + (missedCount π G Z : ℝ) / G.card < τ := by constructor <;> intro h <;> linarith + _ ↔ (missedCount π G Z : ℝ) < τ * G.card := div_lt_iff₀ hcard + +/-- The implication needed for soundness also holds for an empty pool. -/ +theorem readFraction_lt_one_of_exists_missed (π : ScanRule) {G : Finset ℕ} (Z : Cantor) + (h : ∃ a ∈ G, ¬ Reads π a Z) : readFraction π G Z < 1 := by + obtain ⟨a, ha, hmiss⟩ := h + exact (readFraction_lt_one_iff_exists_missed π ⟨a, ha⟩ Z).mpr ⟨a, ha, hmiss⟩ + +/-- The strict count event is empty for an empty pool, so this implication +does not need a nonempty hypothesis. -/ +theorem one_sub_lt_readFraction_of_missedCount_lt (π : ScanRule) (G : Finset ℕ) + (Z : Cantor) (τ : ℝ) (h : (missedCount π G Z : ℝ) < τ * G.card) : + 1 - τ < readFraction π G Z := by + rcases G.eq_empty_or_nonempty with rfl | hG + · simp [missedCount] at h + · exact (one_sub_lt_readFraction_iff_missedCount_lt π hG Z τ).mpr h + +theorem high_failure_eq_missing_event (π : ScanRule) {G : Finset ℕ} + (hG : G.Nonempty) (H : Set Cantor) : + {Z | Z ∈ H ∧ readFraction π G Z < 1} = + {Z | Z ∈ H ∧ ∃ a ∈ G, ¬ Reads π a Z} := by + ext Z + simp only [mem_ofPred_eq, readFraction_lt_one_iff_exists_missed π hG] + +theorem low_failure_eq_missedCount_event (π : ScanRule) {G : Finset ℕ} + (hG : G.Nonempty) (L : Set Cantor) (τ : ℝ) : + {Z | Z ∈ L ∧ 1 - τ < readFraction π G Z} = + {Z | Z ∈ L ∧ (missedCount π G Z : ℝ) < τ * G.card} := by + ext Z + simp only [mem_ofPred_eq, one_sub_lt_readFraction_iff_missedCount_lt π hG] + +end Klr.PoolQuery diff --git a/LeanPool/KLRandomness/PoolParameters.lean b/LeanPool/KLRandomness/PoolParameters.lean new file mode 100644 index 0000000000..db9ace957f --- /dev/null +++ b/LeanPool/KLRandomness/PoolParameters.lean @@ -0,0 +1,275 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.PoolAdviceTables +public import LeanPool.KLRandomness.PoolSoundness +public import LeanPool.KLRandomness.PoolWeighted +import Mathlib.Tactic.Linarith +import Mathlib.Tactic.NormNum +import Mathlib.Tactic.Positivity +import Mathlib.Tactic.Ring + +/-! +# Choosing the finite pool advice before the input size + +The Borel query partition is fixed first. For a finite protected prefix, +an error tolerance, and a position cutoff, this file chooses a rational low +margin, a rational error tolerance and threshold, a finite number of scans, +and concrete finite prefix tables. None of these choices depends on the +requested pool size M. +-/ + +@[expose] public section + +namespace Klr.PoolAdvice + +open Filter MeasureTheory +open scoped BigOperators Topology symmDiff + +/-- All finite data and their analytic guarantees, chosen before the pool size. -/ +structure FixedParameters {π : ℕ → ScanRule} {a : ℕ → ℕ} + (Q : Pool.QueryPartition π a) (ℓ : ℕ) (η : ℝ) (z : ℕ) where + /-- The positive separation margin for the partition estimates. -/ + margin : ℚ + /-- The number of protected scans fixed before the search. -/ + scanCount : ℕ + /-- The finite rational and clopen data given to the pool program. -/ + advice : Advice + margin_pos : 0 < margin + margin_lt_quarter : margin < 1 / 4 + protected_eq : advice.protectedCount = ℓ + protected_le : ℓ ≤ scanCount + position_ge : z ≤ advice.positionBound + error_pos : 0 < advice.error + high_budget : 4 * (advice.error : ℝ) < η + low_budget : η / 3 + 8 * (advice.error : ℝ) / (margin : ℝ) < η + near_one : ∀ i < ℓ, fairCoin.real + {Z | Z ∈ Q.low i ∧ 1 - 2 * (margin : ℝ) ≤ Q.representative i Z} < η / 3 + high_approx : ∀ i < ℓ, + fairCoin.real (Q.high i ∆ highSet advice i) < (advice.error : ℝ) + function_approx : ∀ i < ℓ, + (∫ Z, |approx advice i Z - Q.representative i Z| ∂fairCoin) < (advice.error : ℝ) + approx_bounds : ∀ i < ℓ, ∀ Z, 0 ≤ approx advice i Z ∧ approx advice i Z ≤ 1 + threshold_lower : Pool.weightedQueryLimsup π - + 3 * (protectedWeight advice * (advice.error : ℝ)) < (advice.threshold : ℝ) + threshold_upper : (advice.threshold : ℝ) < Pool.weightedQueryLimsup π - + 2 * (protectedWeight advice * (advice.error : ℝ)) + tail_lt : (1 / 2 : ℝ) ^ scanCount < + (protectedWeight advice * (advice.error : ℝ)) / 4 + position_upper : ∀ b ≥ advice.positionBound, + Pool.weightedQueryProbability π b < Pool.weightedQueryLimsup π + + protectedWeight advice * (advice.error : ℝ) + +/-- All scalar parameters and all finite prefix tables can be chosen jointly, +with the complete finite advice fixed before a later input M. -/ +theorem exists_fixedParameters {π : ℕ → ScanRule} {a : ℕ → ℕ} + (Q : Pool.QueryPartition π a) (ℓ : ℕ) {η : ℝ} (hη : 0 < η) (z : ℕ) : + Nonempty (FixedParameters Q ℓ η z) := by + obtain ⟨τ, hτ0, hτ1, hmargin⟩ := Q.exists_rational_margin ℓ (show 0 < η / 3 by positivity) + have hτr : (0 : ℝ) < τ := by exact_mod_cast hτ0 + obtain ⟨δ, hδ0, hδsmall⟩ := exists_rat_btwn + (show (0 : ℝ) < min (η / 4) (η * (τ : ℝ) / 24) by positivity) + have hδq : (0 : ℚ) < δ := by exact_mod_cast hδ0 + have hδsmall₁ : (δ : ℝ) < η / 4 := hδsmall.trans_le (min_le_left _ _) + have hδsmall₂ : (δ : ℝ) < η * (τ : ℝ) / 24 := hδsmall.trans_le (min_le_right _ _) + have hhigh : 4 * (δ : ℝ) < η := by linarith + have hlow : η / 3 + 8 * (δ : ℝ) / (τ : ℝ) < η := by + have hdiv : 8 * (δ : ℝ) / (τ : ℝ) < η / 3 := by + apply (div_lt_iff₀ hτr).mpr + nlinarith + linarith + let s : ℝ := (1 / 2 : ℝ) ^ ℓ * (δ : ℝ) + have hs : 0 < s := mul_pos (pow_pos (by norm_num) _) hδ0 + obtain ⟨γ, hγlow, hγhigh⟩ := exists_rat_btwn + (show Pool.weightedQueryLimsup π - 3 * s < Pool.weightedQueryLimsup π - 2 * s by linarith) + have htail : ∀ᶠ k : ℕ in atTop, (1 / 2 : ℝ) ^ k < s / 4 := + (tendsto_pow_atTop_nhds_zero_of_lt_one (by norm_num : (0 : ℝ) ≤ 1 / 2) + (by norm_num : (1 / 2 : ℝ) < 1)).eventually (gt_mem_nhds (by positivity)) + obtain ⟨D, hD, hDtail⟩ := ((eventually_ge_atTop ℓ).and htail).exists + obtain ⟨z₀, hz₀⟩ := Pool.exists_weighted_query_upper_cutoff π hs + obtain ⟨A, hAz, hAℓ, hAδ, hAγ, hAtables⟩ := exists_approximating_advice ℓ + (max z z₀) ℓ δ γ hδq (fun i => Q.high i.val) (fun i => Q.measurableSet_high i.val) + (fun i => Q.representative i.val) (fun i => Q.measurable_representative i.val) + (fun i Z => (Q.representative_bounds i.val Z).1) + (fun i Z => (Q.representative_bounds i.val Z).2) + have hsA : protectedWeight A * (A.error : ℝ) = s := by + simp only [protectedWeight, hAℓ, hAδ, s] + refine ⟨{ + margin := τ + scanCount := D + advice := A + margin_pos := hτ0 + margin_lt_quarter := hτ1 + protected_eq := hAℓ + protected_le := hD + position_ge := ?_ + error_pos := ?_ + high_budget := ?_ + low_budget := ?_ + near_one := hmargin + high_approx := ?_ + function_approx := ?_ + approx_bounds := ?_ + threshold_lower := ?_ + threshold_upper := ?_ + tail_lt := ?_ + position_upper := ?_ }⟩ + · rw [hAz] + exact Nat.le_max_left _ _ + · rwa [hAδ] + · rwa [hAδ] + · rwa [hAδ] + · intro i hi + rw [hAδ, symmDiff_comm] + exact (hAtables ⟨i, hi⟩).1 + · intro i hi + rw [hAδ] + exact (hAtables ⟨i, hi⟩).2.2 + · intro i hi Z + exact (hAtables ⟨i, hi⟩).2.1 Z + · rwa [hsA, hAγ] + · rwa [hsA, hAγ] + · rwa [hsA] + · intro b hb + rw [hsA] + exact hz₀ b ((Nat.le_max_right z z₀).trans (by rwa [hAz] at hb)) + +namespace FixedParameters + +variable {π : ℕ → ScanRule} {a : ℕ → ℕ} {Q : Pool.QueryPartition π a} + {ℓ : ℕ} {η : ℝ} {z : ℕ} (P : FixedParameters Q ℓ η z) + +/-- The fixed finite family of actual total computable scans compiled by the search. -/ +def rules : List ScanRule := List.ofFn (fun i : Fin P.scanCount => π i.val) + +@[simp] theorem length_rules : P.rules.length = P.scanCount := List.length_ofFn + +theorem getElem?_rules {i : ℕ} (hi : i < P.scanCount) : P.rules[i]? = some (π i) := by + simp [rules, hi] + +theorem protected_le_length : P.advice.protectedCount ≤ P.rules.length := by + rw [P.protected_eq, P.length_rules] + exact P.protected_le + +theorem error_real_pos : (0 : ℝ) < P.advice.error := by exact_mod_cast P.error_pos + +theorem margin_real_pos : (0 : ℝ) < P.margin := by exact_mod_cast P.margin_pos + +theorem slack_pos : 0 < protectedWeight P.advice * (P.advice.error : ℝ) := + mul_pos (protectedWeight_pos P.advice) P.error_real_pos + +/-- The chosen threshold leaves less than the permitted later-increase budget. -/ +theorem weighted_gap : Pool.weightedQueryLimsup π + + protectedWeight P.advice * (P.advice.error : ℝ) - (P.advice.threshold : ℝ) < + 4 * protectedWeight P.advice * (P.advice.error : ℝ) := by + have h := P.threshold_lower + nlinarith + +/-- The geometric tail is small enough for the finite weighted limit to be +strictly above the acceptance threshold. -/ +theorem threshold_add_tail_lt : + (P.advice.threshold : ℝ) + (1 / 2 : ℝ) ^ P.scanCount < Pool.weightedQueryLimsup π := by + have h₁ := P.threshold_upper + have h₂ := P.tail_lt + have h₃ := P.slack_pos + linarith + +/-- The rational and real weight conventions coincide. -/ +theorem cast_weight_eq (i : ℕ) : (PoolAdvice.weight i : ℝ) = Pool.weight i := by + simp [PoolAdvice.weight, Pool.weight] + +/-- The strict near-one strip used in the L1 argument is bounded by the +fixed low-set strip used to choose the margin. -/ +theorem near_one_strict {i : ℕ} (hi : i < ℓ) : + fairCoin.real {Z | 1 - 2 * (P.margin : ℝ) < Q.representative i Z ∧ + Q.representative i Z < 1} < η / 3 := by + apply lt_of_le_of_lt (measureReal_mono (μ := fairCoin) ?_) (P.near_one i hi) + intro Z hZ + refine ⟨?_, hZ.1.le⟩ + change Q.representative i Z ≠ 1 + exact ne_of_lt hZ.2 + +/-- Fixed representatives are integrable on the probability space. -/ +theorem integrable_representative (i : ℕ) : Integrable (Q.representative i) fairCoin := + (Pool.integrable_L2 (Q.limit i)).congr (Q.representative_ae_eq i).symm + +/-- The cutoff controls final weighted coverage for every finite pool beyond +it, including the empty pool. This is the global bound used for soundness. -/ +theorem final_weighted_bound (G : Finset ℕ) + (hG : ∀ b ∈ G, P.advice.positionBound ≤ b) : + (∑ i ∈ Finset.range P.scanCount, + (PoolAdvice.weight i : ℝ) * ∫ Z, PoolQuery.readFraction (π i) G Z ∂fairCoin) ≤ + Pool.weightedQueryLimsup π + protectedWeight P.advice * (P.advice.error : ℝ) := by + have hInt (i : ℕ) : (∫ Z, PoolQuery.readFraction (π i) G Z ∂fairCoin) = + (∑ b ∈ G, Pool.queryProbability (π i) b) / G.card := by + unfold PoolQuery.readFraction Pool.queryProbability + rw [integral_div, + integral_finsetSum _ (fun b _ => PoolQuery.integrable_indicator (π i) b)] + simp_rw [hInt, cast_weight_eq, ← mul_div_assoc, Finset.mul_sum] + rw [← Finset.sum_div, Finset.sum_comm] + by_cases hcard : G.card = 0 + · simp only [hcard, Nat.cast_zero, div_zero] + exact add_nonneg (Pool.weightedQueryLimsup_bounds π).1 P.slack_pos.le + · apply (div_le_iff₀ (by exact_mod_cast Nat.pos_of_ne_zero hcard)).mpr + calc + _ ≤ ∑ _b ∈ G, (Pool.weightedQueryLimsup π + + protectedWeight P.advice * (P.advice.error : ℝ)) := by + apply Finset.sum_le_sum + intro b hb + exact (sub_nonneg.mp (Pool.weighted_query_truncation π b P.scanCount).1).trans + (P.position_upper b (hG b hb)).le + _ = _ := by simp only [Finset.sum_const, nsmul_eq_mul]; ring + +/-- Every accepted pair satisfies both final measure estimates on the fixed +Borel partition. The finite tables are used only inside the computation. -/ +theorem accepted_measure_bounds {M : ℕ} {C : Candidate} + (h : Accepted P.rules P.advice M C) : + ∀ i < ℓ, + fairCoin.real {Z | Z ∈ Q.high i ∧ PoolQuery.readFraction (π i) C.1.toFinset Z < 1} < η ∧ + fairCoin.real {Z | Z ∈ Q.low i ∧ + 1 - (P.margin : ℝ) < PoolQuery.readFraction (π i) C.1.toFinset Z} < η := by + have hπ : ∀ i < P.rules.length, P.rules[i]? = some (π i) := by + intro i hi + exact P.getElem?_rules (by simpa only [P.length_rules] using hi) + have hbound : (∑ i ∈ Finset.range P.rules.length, + (PoolAdvice.weight i : ℝ) * + ∫ Z, PoolQuery.readFraction (π i) C.1.toFinset Z ∂fairCoin) ≤ + Pool.weightedQueryLimsup π + protectedWeight P.advice * (P.advice.error : ℝ) := by + rw [P.length_rules] + exact P.final_weighted_bound _ (fun b hb => h.2.2.1 b (List.mem_toFinset.mp hb)) + intro i hi + have hi' : i < P.advice.protectedCount := by rwa [P.protected_eq] + refine ⟨?_, ?_⟩ + · exact (h.high_failure_lt π hπ P.protected_le_length hi' (P.high_approx i hi)).trans + P.high_budget + · have hlow := h.low_near_full_lt π hπ P.protected_le_length hbound P.weighted_gap hi' + (integrable_representative (Q := Q) i) (P.function_approx i hi) P.margin_real_pos + (P.near_one_strict hi) + apply lt_of_le_of_lt (measureReal_mono (μ := fairCoin) ?_) (hlow.trans P.low_budget) + intro Z hZ + exact ⟨Q.representative_lt_one_on_low i hZ.1, hZ.2⟩ + +/-- The chosen finite scan prefix eventually has sufficient weighted mass +along the fixed position subsequence. -/ +theorem eventually_weighted_above + (hp : Tendsto (Pool.weightedQueryProbability π ∘ Q.position) atTop + (𝓝 (Pool.weightedQueryLimsup π))) : + ∀ᶠ n : ℕ in atTop, (P.advice.threshold : ℝ) < + ∑ i ∈ Finset.range P.rules.length, + Pool.weight i * Pool.queryProbability (π i) (Q.position n) := by + obtain ⟨ε, hε, hev⟩ := Q.eventually_finite_weighted_above hp P.scanCount + P.threshold_add_tail_lt + filter_upwards [hev] with n hn + rw [P.length_rules] + linarith + +end FixedParameters + +end Klr.PoolAdvice diff --git a/LeanPool/KLRandomness/PoolPartition.lean b/LeanPool/KLRandomness/PoolPartition.lean new file mode 100644 index 0000000000..bce531d2bb --- /dev/null +++ b/LeanPool/KLRandomness/PoolPartition.lean @@ -0,0 +1,168 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.PoolWeakLimit +public import Mathlib.Analysis.SpecificLimits.Basic +public import Mathlib.MeasureTheory.Measure.Continuity +import Mathlib.Tactic.Linarith +import Mathlib.Tactic.NormNum +import Mathlib.Tactic.Positivity +import Mathlib.Tactic.Ring + +/-! +# Fixed measurable partitions from weak limits + +The pool lemma needs one partition for each scanning rule, fixed before the +finite stage parameters are chosen. Given the weak limits constructed in +`PoolWeakLimit`, take `H = {g = 1}` and `L = Hᶜ`. These are measurable sets; +on Cantor space they are Borel sets. + +Weak convergence makes the missed mass on `H` tend to zero. On `L`, the mass +where `g` is arbitrarily close to one tends to zero. A single positive rational +threshold works simultaneously for any prescribed finite list of limits. +-/ + +@[expose] public section + +noncomputable section + +namespace Klr.Pool + +open Filter MeasureTheory Set Topology +open scoped ENNReal + +variable {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} + +/-- The high part of the fixed partition belonging to a weak limit. -/ +def highSet (g : Lp ℝ 2 μ) : Set Ω := {x | g x = 1} + +/-- The low part of the same fixed partition. -/ +def lowSet (g : Lp ℝ 2 μ) : Set Ω := (highSet g)ᶜ + +/-- Points in the low part whose weak-limit value is at least `1 - δ`. -/ +def nearOneLowSet (g : Lp ℝ 2 μ) (δ : ℝ) : Set Ω := + lowSet g ∩ {x | 1 - δ ≤ g x} + +theorem measurableSet_highSet (g : Lp ℝ 2 μ) : MeasurableSet (highSet g) := + (Lp.stronglyMeasurable g).measurableSet_eq_fun stronglyMeasurable_const + +theorem measurableSet_lowSet (g : Lp ℝ 2 μ) : MeasurableSet (lowSet g) := + (measurableSet_highSet g).compl + +theorem measurableSet_nearOneLowSet (g : Lp ℝ 2 μ) (δ : ℝ) : + MeasurableSet (nearOneLowSet g δ) := + (measurableSet_lowSet g).inter + (measurableSet_le measurable_const (Lp.stronglyMeasurable g).measurable) + +theorem disjoint_highSet_lowSet (g : Lp ℝ 2 μ) : Disjoint (highSet g) (lowSet g) := + disjoint_compl_right + +theorem highSet_union_lowSet (g : Lp ℝ 2 μ) : highSet g ∪ lowSet g = univ := + union_compl_self _ + +theorem setIntegral_highSet (g : Lp ℝ 2 μ) : + ∫ x in highSet g, g x ∂μ = μ.real (highSet g) := by + calc + ∫ x in highSet g, g x ∂μ = ∫ _ in highSet g, (1 : ℝ) ∂μ := + setIntegral_congr_fun (measurableSet_highSet g) fun _ hx => hx + _ = μ.real (highSet g) := by simp + +variable [IsFiniteMeasure μ] + +/-- On the high part, the set integral of `1 - uₙ` tends to zero. -/ +theorem WeaklyConverges.high_deficit {u : ℕ → Lp ℝ 2 μ} {g : Lp ℝ 2 μ} + (hu : WeaklyConverges u g) : + Tendsto (fun n => μ.real (highSet g) - ∫ x in highSet g, u n x ∂μ) + atTop (𝓝 0) := by + simpa only [setIntegral_highSet, sub_self] using + (tendsto_const_nhds (x := μ.real (highSet g))).sub + (hu.setIntegral (measurableSet_highSet g)) + +/-- For indicator sequences, the deficit is exactly the high-set mass missed by +the corresponding event. -/ +theorem high_deficit_indicator (g : Lp ℝ 2 μ) {A : Set Ω} (hA : MeasurableSet A) : + μ.real (highSet g) - + ∫ x in highSet g, indicatorConstLp 2 hA (measure_ne_top μ A) (1 : ℝ) x ∂μ = + μ.real (highSet g \ A) := by + rw [setIntegral_indicatorConstLp (measurableSet_highSet g)] + simp only [smul_eq_mul, mul_one, Set.inter_comm A] + have h := measureReal_inter_add_sdiff (μ := μ) (s := highSet g) hA + linarith + +/-- The missed mass on the one fixed high set tends to zero along the common +weakly convergent subsequence of query indicators. -/ +theorem high_miss_tendsto_zero (A : ℕ → Set Ω) (hA : ∀ n, MeasurableSet (A n)) + {g : Lp ℝ 2 μ} + (hu : WeaklyConverges + (fun n => indicatorConstLp 2 (hA n) (measure_ne_top μ (A n)) (1 : ℝ)) g) : + Tendsto (fun n => μ.real (highSet g \ A n)) atTop (𝓝 0) := by + simpa only [high_deficit_indicator] using hu.high_deficit + +/-- The low part has vanishing mass arbitrarily close to the value one. The +upper bound on `g` is required only almost everywhere. -/ +theorem tendsto_measure_nearOneLowSet (g : Lp ℝ 2 μ) + (hg1 : ∀ᵐ x ∂μ, g x ≤ 1) : + Tendsto (fun n : ℕ => μ (nearOneLowSet g ((1 / 2 : ℝ) ^ n))) atTop (𝓝 0) := by + let s : ℕ → Set Ω := fun n => nearOneLowSet g ((1 / 2 : ℝ) ^ n) + have hs : ∀ n, NullMeasurableSet (s n) μ := + fun n => (measurableSet_nearOneLowSet g _).nullMeasurableSet + have hm : Antitone s := by + intro n m hnm x hxm + refine ⟨hxm.1, ?_⟩ + have hp : (1 / 2 : ℝ) ^ m ≤ (1 / 2 : ℝ) ^ n := + pow_le_pow_of_le_one (by norm_num) (by norm_num) hnm + exact (sub_le_sub_left hp 1).trans hxm.2 + have hz : μ (⋂ n, s n) = 0 := by + rw [measure_eq_zero_iff_ae_notMem] + filter_upwards [hg1] with x hx1 + intro hx + have hxlow : g x ≠ 1 := (mem_iInter.mp hx 0).1 + have hxnear : ∀ n, 1 - (1 / 2 : ℝ) ^ n ≤ g x := fun n => (mem_iInter.mp hx n).2 + have ht : Tendsto (fun n : ℕ => 1 - (1 / 2 : ℝ) ^ n) atTop (𝓝 1) := by + simpa only [sub_zero] using tendsto_const_nhds.sub + (tendsto_pow_atTop_nhds_zero_of_lt_one (by norm_num : (0 : ℝ) ≤ 1 / 2) + (by norm_num : (1 / 2 : ℝ) < 1)) + exact hxlow (le_antisymm hx1 (le_of_tendsto' ht hxnear)) + simpa only [hz, Function.comp_def, s] using + tendsto_measure_iInter_atTop hs hm ⟨0, measure_ne_top μ _⟩ + +theorem tendsto_measureReal_nearOneLowSet (g : Lp ℝ 2 μ) + (hg1 : ∀ᵐ x ∂μ, g x ≤ 1) : + Tendsto (fun n : ℕ => μ.real (nearOneLowSet g ((1 / 2 : ℝ) ^ n))) + atTop (𝓝 0) := by + simpa only [ENNReal.toReal_zero, Measure.real, Function.comp_def] using + (ENNReal.tendsto_toReal ENNReal.zero_ne_top).comp (tendsto_measure_nearOneLowSet g hg1) + +/-- A single positive rational margin works for finitely many fixed low sets. +It is chosen from the limits and the error tolerance, independently of any +eventual pool size. -/ +theorem exists_rational_low_margin (g : ℕ → Lp ℝ 2 μ) + (hg1 : ∀ i, ∀ᵐ x ∂μ, g i x ≤ 1) (ℓ : ℕ) {η : ℝ} (hη : 0 < η) : + ∃ τ : ℚ, 0 < τ ∧ τ < 1 / 4 ∧ + ∀ i < ℓ, μ.real (nearOneLowSet (g i) (2 * (τ : ℝ))) < η := by + have hev : ∀ᶠ n : ℕ in atTop, + ∀ i : Fin ℓ, μ.real (nearOneLowSet (g i) ((1 / 2 : ℝ) ^ n)) < η := by + exact Filter.eventually_all.mpr fun i => + (tendsto_measureReal_nearOneLowSet (g i) (hg1 i)).eventually (gt_mem_nhds hη) + obtain ⟨n, hn, hsmall⟩ := ((eventually_ge_atTop 2).and hev).exists + refine ⟨(1 / 2 : ℚ) ^ (n + 1), by positivity, ?_, ?_⟩ + · have hp : (1 / 2 : ℚ) ^ (n + 1) ≤ (1 / 2 : ℚ) ^ 3 := + pow_le_pow_of_le_one (by norm_num) (by norm_num) (by omega) + norm_num at hp ⊢ + linarith + · intro i hi + have heq : 2 * (((1 / 2 : ℚ) ^ (n + 1) : ℚ) : ℝ) = (1 / 2 : ℝ) ^ n := by + push_cast + rw [pow_succ] + ring + rw [heq] + exact hsmall ⟨i, hi⟩ + +end Klr.Pool diff --git a/LeanPool/KLRandomness/PoolPartitionQuery.lean b/LeanPool/KLRandomness/PoolPartitionQuery.lean new file mode 100644 index 0000000000..c1af17cccb --- /dev/null +++ b/LeanPool/KLRandomness/PoolPartitionQuery.lean @@ -0,0 +1,165 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.PoolPartitionRepresentative +public import LeanPool.KLRandomness.PoolQuery + +/-! +# Fixed Borel partitions for the actual query indicators + +This file applies the Hilbert-space compactness theorem to the actual events +`PoolQuery.Reads`. The resulting partitions depend only on the countable scan +family and the initial sequence of positions. In particular, their choice +precedes the finite prefix of scans, the error tolerance, and the pool size. + +The same extraction preserves convergence of any scalar statistic previously +arranged along the initial sequence, including the weighted query probability. +-/ + +@[expose] public section + +noncomputable section + +namespace Klr.Pool + +open Filter MeasureTheory Set Topology +open scoped ENNReal + +/-- The actual eventual-query indicator as an `L²` vector. -/ +def queryL2 (π : ScanRule) (a : ℕ) : Lp ℝ 2 fairCoin := + indicatorConstLp 2 (PoolQuery.measurableSet_reads π a) + (measure_ne_top fairCoin _) (1 : ℝ) + +theorem queryL2_coeFn (π : ScanRule) (a : ℕ) : + queryL2 π a =ᵐ[fairCoin] PoolQuery.indicator π a := + indicatorConstLp_coeFn + +theorem queryL2_nonneg (π : ScanRule) (a : ℕ) : + ∀ᵐ Z ∂fairCoin, 0 ≤ queryL2 π a Z := by + filter_upwards [queryL2_coeFn π a] with Z hZ + rw [hZ] + exact (PoolQuery.indicator_bounds π a Z).1 + +theorem queryL2_le_one (π : ScanRule) (a : ℕ) : + ∀ᵐ Z ∂fairCoin, queryL2 π a Z ≤ 1 := by + filter_upwards [queryL2_coeFn π a] with Z hZ + rw [hZ] + exact (PoolQuery.indicator_bounds π a Z).2 + +theorem norm_queryL2_le_one (π : ScanRule) (a : ℕ) : ‖queryL2 π a‖ ≤ 1 := + norm_le_one_of_ae_unitInterval (queryL2_nonneg π a) (queryL2_le_one π a) + +/-- The common weak limits and their subsequence, obtained from the actual +query indicators. `exists_queryPartition` proves this structure inhabited. -/ +structure QueryPartition (π : ℕ → ScanRule) (a : ℕ → ℕ) where + /-- The common subsequence of query positions used for weak convergence. -/ + subseq : ℕ → ℕ + subseq_strictMono : StrictMono subseq + /-- Weak limit in the fair-coin Hilbert space for each scan. -/ + limit : ℕ → Lp ℝ 2 fairCoin + weak : ∀ i, WeaklyConverges (fun n => queryL2 (π i) (a (subseq n))) (limit i) + limit_nonneg : ∀ i, ∀ᵐ Z ∂fairCoin, 0 ≤ limit i Z + limit_le_one : ∀ i, ∀ᵐ Z ∂fairCoin, limit i Z ≤ 1 + +/-- Genuine existence of the common weak limits, using only Mathlib's +Banach--Alaoglu and Riesz theorems and the actual query events. -/ +theorem exists_queryPartition (π : ℕ → ScanRule) (a : ℕ → ℕ) : + Nonempty (QueryPartition π a) := by + obtain ⟨φ, g, hφ, hweak, hg0, hg1⟩ := + exists_unitInterval_weak_limits (fun i n => queryL2 (π i) (a n)) + (fun i n => queryL2_nonneg (π i) (a n)) + (fun i n => queryL2_le_one (π i) (a n)) + exact ⟨⟨φ, hφ, g, hweak, hg0, hg1⟩⟩ + +namespace QueryPartition + +variable {π : ℕ → ScanRule} {a : ℕ → ℕ} (D : QueryPartition π a) + +/-- The common sequence of positions after weak-limit extraction. -/ +def position (n : ℕ) : ℕ := a (D.subseq n) + +/-- The Borel representative used in the fixed partition. -/ +def representative (i : ℕ) : Cantor → ℝ := clippedRepresentative (D.limit i) + +/-- The fixed Borel high set. -/ +def high (i : ℕ) : Set Cantor := clippedHighSet (D.limit i) + +/-- The complementary fixed Borel low set. -/ +def low (i : ℕ) : Set Cantor := clippedLowSet (D.limit i) + +theorem measurable_representative (i : ℕ) : Measurable (D.representative i) := + measurable_clippedRepresentative _ + +theorem representative_bounds (i : ℕ) (Z : Cantor) : + 0 ≤ D.representative i Z ∧ D.representative i Z ≤ 1 := + clippedRepresentative_bounds _ _ + +theorem representative_ae_eq (i : ℕ) : + D.representative i =ᵐ[fairCoin] D.limit i := + clippedRepresentative_ae_eq _ (D.limit_nonneg i) (D.limit_le_one i) + +theorem measurableSet_high (i : ℕ) : MeasurableSet (D.high i) := + measurableSet_clippedHighSet _ + +theorem measurableSet_low (i : ℕ) : MeasurableSet (D.low i) := + measurableSet_clippedLowSet _ + +theorem disjoint_high_low (i : ℕ) : Disjoint (D.high i) (D.low i) := + disjoint_clippedHighSet_clippedLowSet _ + +theorem high_union_low (i : ℕ) : D.high i ∪ D.low i = univ := + clippedHighSet_union_clippedLowSet _ + +theorem representative_eq_one_on_high (i : ℕ) {Z : Cantor} (hZ : Z ∈ D.high i) : + D.representative i Z = 1 := hZ + +theorem representative_lt_one_on_low (i : ℕ) {Z : Cantor} (hZ : Z ∈ D.low i) : + D.representative i Z < 1 := clippedRepresentative_lt_one_on_low _ hZ + +theorem low_eq_lt_one (i : ℕ) : D.low i = {Z | D.representative i Z < 1} := by + ext Z + constructor + · exact D.representative_lt_one_on_low i + · exact fun hZ => ne_of_lt hZ + +theorem positions_strictMono (ha : StrictMono a) : StrictMono D.position := + ha.comp D.subseq_strictMono + +theorem positions_tendsto (ha : Tendsto a atTop atTop) : + Tendsto D.position atTop atTop := ha.comp D.subseq_strictMono.tendsto_atTop + +/-- Any scalar convergence arranged along the starting positions survives the +one common weak-limit extraction. -/ +theorem scalar_tendsto {p : ℕ → ℝ} {pstar : ℝ} + (hp : Tendsto (p ∘ a) atTop (𝓝 pstar)) : + Tendsto (p ∘ D.position) atTop (𝓝 pstar) := + hp.comp D.subseq_strictMono.tendsto_atTop + +/-- On each fixed high set, the probability of missing the current position +tends to zero along the actual query subsequence. -/ +theorem high_miss_tendsto_zero (i : ℕ) : + Tendsto (fun n => fairCoin.real (D.high i \ {Z | PoolQuery.Reads (π i) (D.position n) Z})) + atTop (𝓝 0) := + clipped_high_miss_tendsto_zero + (fun n => {Z | PoolQuery.Reads (π i) (D.position n) Z}) + (fun n => PoolQuery.measurableSet_reads (π i) (D.position n)) + (D.weak i) (D.limit_nonneg i) (D.limit_le_one i) + +/-- One positive rational margin works for a finite prefix of the fixed low +sets, independently of the subsequently chosen pool size. -/ +theorem exists_rational_margin (ℓ : ℕ) {η : ℝ} (hη : 0 < η) : + ∃ τ : ℚ, 0 < τ ∧ τ < 1 / 4 ∧ + ∀ i < ℓ, fairCoin.real + {Z | Z ∈ D.low i ∧ 1 - 2 * (τ : ℝ) ≤ D.representative i Z} < η := + exists_rational_clipped_low_margin D.limit D.limit_nonneg D.limit_le_one ℓ hη + +end QueryPartition + +end Klr.Pool diff --git a/LeanPool/KLRandomness/PoolPartitionRepresentative.lean b/LeanPool/KLRandomness/PoolPartitionRepresentative.lean new file mode 100644 index 0000000000..0e935e0a8a --- /dev/null +++ b/LeanPool/KLRandomness/PoolPartitionRepresentative.lean @@ -0,0 +1,154 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.PoolPartition +import Mathlib.Tactic.NormNum + +/-! +# Pointwise bounded Borel representatives + +`L²` bounds are naturally almost everywhere statements. Clipping the chosen +measurable representative into `[0,1]` gives an everywhere bounded Borel +function representing the same `L²` vector. The clipped high and low sets +have the same measures and asymptotic properties as the sets constructed in +`PoolPartition`. +-/ + +@[expose] public section + +noncomputable section + +namespace Klr.Pool + +open Filter MeasureTheory Set Topology +open scoped ENNReal + +variable {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} + +/-- An everywhere `[0,1]`-valued representative of an almost everywhere bounded +weak limit. -/ +def clippedRepresentative (g : Lp ℝ 2 μ) (x : Ω) : ℝ := + min 1 (max 0 (g x)) + +theorem measurable_clippedRepresentative (g : Lp ℝ 2 μ) : + Measurable (clippedRepresentative g) := + measurable_const.min (measurable_const.max (Lp.stronglyMeasurable g).measurable) + +theorem clippedRepresentative_bounds (g : Lp ℝ 2 μ) (x : Ω) : + 0 ≤ clippedRepresentative g x ∧ clippedRepresentative g x ≤ 1 := + ⟨le_min (by norm_num) (le_max_left _ _), min_le_left _ _⟩ + +theorem clippedRepresentative_ae_eq (g : Lp ℝ 2 μ) + (hg0 : ∀ᵐ x ∂μ, 0 ≤ g x) (hg1 : ∀ᵐ x ∂μ, g x ≤ 1) : + clippedRepresentative g =ᵐ[μ] g := by + filter_upwards [hg0, hg1] with x hx0 hx1 + simp only [clippedRepresentative, max_eq_right hx0, min_eq_right hx1] + +theorem memLp_clippedRepresentative (g : Lp ℝ 2 μ) + (hg0 : ∀ᵐ x ∂μ, 0 ≤ g x) (hg1 : ∀ᵐ x ∂μ, g x ≤ 1) : + MemLp (clippedRepresentative g) 2 μ := + (memLp_congr_ae (clippedRepresentative_ae_eq g hg0 hg1)).mpr (Lp.memLp g) + +theorem clippedRepresentative_toLp (g : Lp ℝ 2 μ) + (hg0 : ∀ᵐ x ∂μ, 0 ≤ g x) (hg1 : ∀ᵐ x ∂μ, g x ≤ 1) : + (memLp_clippedRepresentative g hg0 hg1).toLp (clippedRepresentative g) = g := by + exact Lp.ext ((memLp_clippedRepresentative g hg0 hg1).coeFn_toLp.trans + (clippedRepresentative_ae_eq g hg0 hg1)) + +/-- The fixed high set defined from the everywhere bounded representative. -/ +def clippedHighSet (g : Lp ℝ 2 μ) : Set Ω := {x | clippedRepresentative g x = 1} + +/-- The complementary fixed low set. -/ +def clippedLowSet (g : Lp ℝ 2 μ) : Set Ω := (clippedHighSet g)ᶜ + +/-- The near-one part of the clipped low set. -/ +def clippedNearOneLowSet (g : Lp ℝ 2 μ) (δ : ℝ) : Set Ω := + clippedLowSet g ∩ {x | 1 - δ ≤ clippedRepresentative g x} + +theorem measurableSet_clippedHighSet (g : Lp ℝ 2 μ) : + MeasurableSet (clippedHighSet g) := + measurableSet_eq_fun (measurable_clippedRepresentative g) measurable_const + +theorem measurableSet_clippedLowSet (g : Lp ℝ 2 μ) : + MeasurableSet (clippedLowSet g) := + (measurableSet_clippedHighSet g).compl + +theorem measurableSet_clippedNearOneLowSet (g : Lp ℝ 2 μ) (δ : ℝ) : + MeasurableSet (clippedNearOneLowSet g δ) := + (measurableSet_clippedLowSet g).inter + (measurableSet_le measurable_const (measurable_clippedRepresentative g)) + +theorem clippedRepresentative_lt_one_on_low (g : Lp ℝ 2 μ) {x : Ω} + (hx : x ∈ clippedLowSet g) : clippedRepresentative g x < 1 := by + exact lt_of_le_of_ne (clippedRepresentative_bounds g x).2 hx + +theorem disjoint_clippedHighSet_clippedLowSet (g : Lp ℝ 2 μ) : + Disjoint (clippedHighSet g) (clippedLowSet g) := disjoint_compl_right + +theorem clippedHighSet_union_clippedLowSet (g : Lp ℝ 2 μ) : + clippedHighSet g ∪ clippedLowSet g = univ := union_compl_self _ + +theorem clippedHighSet_ae_eq (g : Lp ℝ 2 μ) + (hg0 : ∀ᵐ x ∂μ, 0 ≤ g x) (hg1 : ∀ᵐ x ∂μ, g x ≤ 1) : + clippedHighSet g =ᵐ[μ] highSet g := by + filter_upwards [clippedRepresentative_ae_eq g hg0 hg1] with x hx + simp only [clippedHighSet, highSet, mem_ofPred_eq, hx] + +theorem clippedNearOneLowSet_ae_eq (g : Lp ℝ 2 μ) + (hg0 : ∀ᵐ x ∂μ, 0 ≤ g x) (hg1 : ∀ᵐ x ∂μ, g x ≤ 1) (δ : ℝ) : + clippedNearOneLowSet g δ =ᵐ[μ] nearOneLowSet g δ := by + filter_upwards [clippedRepresentative_ae_eq g hg0 hg1] with x hx + simp only [clippedNearOneLowSet, nearOneLowSet, clippedLowSet, lowSet, + clippedHighSet, highSet, mem_inter_iff, mem_compl_iff, mem_ofPred_eq, hx] + +theorem measureReal_clippedNearOneLowSet (g : Lp ℝ 2 μ) + (hg0 : ∀ᵐ x ∂μ, 0 ≤ g x) (hg1 : ∀ᵐ x ∂μ, g x ≤ 1) (δ : ℝ) : + μ.real (clippedNearOneLowSet g δ) = μ.real (nearOneLowSet g δ) := + measureReal_congr (clippedNearOneLowSet_ae_eq g hg0 hg1 δ) + +theorem setIntegral_clippedHighSet (g : Lp ℝ 2 μ) + (hg0 : ∀ᵐ x ∂μ, 0 ≤ g x) (hg1 : ∀ᵐ x ∂μ, g x ≤ 1) : + ∫ x in clippedHighSet g, g x ∂μ = μ.real (clippedHighSet g) := by + calc + ∫ x in clippedHighSet g, g x ∂μ = + ∫ x in clippedHighSet g, clippedRepresentative g x ∂μ := + integral_congr_ae (ae_restrict_of_ae (clippedRepresentative_ae_eq g hg0 hg1).symm) + _ = ∫ _ in clippedHighSet g, (1 : ℝ) ∂μ := + setIntegral_congr_fun (measurableSet_clippedHighSet g) fun _ hx => hx + _ = μ.real (clippedHighSet g) := by simp + +variable [IsFiniteMeasure μ] + +theorem clipped_high_miss_tendsto_zero (A : ℕ → Set Ω) + (hA : ∀ n, MeasurableSet (A n)) {g : Lp ℝ 2 μ} + (hu : WeaklyConverges + (fun n => indicatorConstLp 2 (hA n) (measure_ne_top μ (A n)) (1 : ℝ)) g) + (hg0 : ∀ᵐ x ∂μ, 0 ≤ g x) (hg1 : ∀ᵐ x ∂μ, g x ≤ 1) : + Tendsto (fun n => μ.real (clippedHighSet g \ A n)) atTop (𝓝 0) := by + have heq (n : ℕ) : μ.real (clippedHighSet g \ A n) = μ.real (highSet g \ A n) := + measureReal_congr ((clippedHighSet_ae_eq g hg0 hg1).diff EventuallyEqSet.rfl) + simpa only [heq] using high_miss_tendsto_zero A hA hu + +theorem tendsto_measureReal_clippedNearOneLowSet (g : Lp ℝ 2 μ) + (hg0 : ∀ᵐ x ∂μ, 0 ≤ g x) (hg1 : ∀ᵐ x ∂μ, g x ≤ 1) : + Tendsto (fun n : ℕ => μ.real (clippedNearOneLowSet g ((1 / 2 : ℝ) ^ n))) + atTop (𝓝 0) := by + simpa only [measureReal_clippedNearOneLowSet g hg0 hg1] using + tendsto_measureReal_nearOneLowSet g hg1 + +theorem exists_rational_clipped_low_margin (g : ℕ → Lp ℝ 2 μ) + (hg0 : ∀ i, ∀ᵐ x ∂μ, 0 ≤ g i x) (hg1 : ∀ i, ∀ᵐ x ∂μ, g i x ≤ 1) + (ℓ : ℕ) {η : ℝ} (hη : 0 < η) : + ∃ τ : ℚ, 0 < τ ∧ τ < 1 / 4 ∧ + ∀ i < ℓ, μ.real (clippedNearOneLowSet (g i) (2 * (τ : ℝ))) < η := by + simpa only [measureReal_clippedNearOneLowSet (g _) (hg0 _) (hg1 _)] using + exists_rational_low_margin g hg1 ℓ hη + +end Klr.Pool diff --git a/LeanPool/KLRandomness/PoolQuery.lean b/LeanPool/KLRandomness/PoolQuery.lean new file mode 100644 index 0000000000..3d8ff49c3d --- /dev/null +++ b/LeanPool/KLRandomness/PoolQuery.lean @@ -0,0 +1,209 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.DropEvents +public import LeanPool.KLRandomness.ComputableNonrandom +public import Mathlib.MeasureTheory.Integral.DominatedConvergence +import Mathlib.Tactic.Linarith + +/-! +# Query indicators on answer space + +The pool lemma feeds the same answer sequence to several scan rules. Its +probability space is therefore answer space, rather than the original input +space of an adaptive run. The query at time `t` is the rule applied directly +to the first `t` prescribed answers. + +Every finite pool's coverage fraction stabilizes pointwise at a finite +horizon (depending on the answer sequence). The actual finite-horizon +fractions converge in L¹, as required by the pool search's termination proof. +-/ + +@[expose] public section + +namespace Klr.PoolQuery + +open MeasureTheory Filter +open scoped Topology BigOperators + +/-- The query made after the first `t` bits of a prescribed answer sequence. -/ +def queryAt (π : ScanRule) (Z : Cantor) (t : ℕ) : ℕ := + π.query (ScanRule.inputPrefix Z t) + +/-- A position is queried before a finite horizon. -/ +def ReadsBy (π : ScanRule) (a V : ℕ) (Z : Cantor) : Prop := + ∃ t < V, queryAt π Z t = a + +/-- A position is queried at some time on the prescribed answer sequence. -/ +def Reads (π : ScanRule) (a : ℕ) (Z : Cantor) : Prop := + ∃ t, queryAt π Z t = a + +theorem measurable_queryAt (π : ScanRule) (t : ℕ) : + Measurable (fun Z => queryAt π Z t) := by + simpa only [ScanRule.monotone_transcript, queryAt] using + DropEvents.measurable_transcript_eval ScanRule.monotone t π.query + +theorem measurableSet_readsBy (π : ScanRule) (a V : ℕ) : + MeasurableSet {Z | ReadsBy π a V Z} := by + have he : {Z | ReadsBy π a V Z} = + ⋃ t : Fin V, {Z | queryAt π Z t.val = a} := by + ext Z + simp only [ReadsBy, Set.mem_ofPred_eq, Set.mem_iUnion] + exact ⟨fun ⟨t, ht, h⟩ => ⟨⟨t, ht⟩, h⟩, + fun ⟨t, h⟩ => ⟨t.val, t.isLt, h⟩⟩ + rw [he] + exact MeasurableSet.iUnion fun t => (measurable_queryAt π t.val) (measurableSet_singleton a) + +theorem measurableSet_reads (π : ScanRule) (a : ℕ) : + MeasurableSet {Z | Reads π a Z} := by + have he : {Z | Reads π a Z} = ⋃ t : ℕ, {Z | queryAt π Z t = a} := by + ext Z + simp [Reads] + rw [he] + exact MeasurableSet.iUnion fun t => (measurable_queryAt π t) (measurableSet_singleton a) + +theorem readsBy_mono (π : ScanRule) (a : ℕ) {V W : ℕ} (hVW : V ≤ W) {Z : Cantor} + (h : ReadsBy π a V Z) : ReadsBy π a W Z := by + obtain ⟨t, ht, hq⟩ := h + exact ⟨t, lt_of_lt_of_le ht hVW, hq⟩ + +theorem reads_of_readsBy {π : ScanRule} {a V : ℕ} {Z : Cantor} + (h : ReadsBy π a V Z) : Reads π a Z := by + obtain ⟨t, _, ht⟩ := h + exact ⟨t, ht⟩ + +/-- The indicator of eventual querying, denoted `g_{i,a}` in the paper. -/ +noncomputable def indicator (π : ScanRule) (a : ℕ) : Cantor → ℝ := + {Z | Reads π a Z}.indicator (fun _ => 1) + +/-- The finite-horizon query indicator. -/ +noncomputable def indicatorBy (π : ScanRule) (a V : ℕ) : Cantor → ℝ := + {Z | ReadsBy π a V Z}.indicator (fun _ => 1) + +theorem measurable_indicator (π : ScanRule) (a : ℕ) : Measurable (indicator π a) := + measurable_const.indicator (measurableSet_reads π a) + +theorem measurable_indicatorBy (π : ScanRule) (a V : ℕ) : Measurable (indicatorBy π a V) := + measurable_const.indicator (measurableSet_readsBy π a V) + +theorem indicator_bounds (π : ScanRule) (a : ℕ) (Z : Cantor) : + 0 ≤ indicator π a Z ∧ indicator π a Z ≤ 1 := by + classical + by_cases h : Reads π a Z <;> simp [indicator, h] + +theorem indicatorBy_bounds (π : ScanRule) (a V : ℕ) (Z : Cantor) : + 0 ≤ indicatorBy π a V Z ∧ indicatorBy π a V Z ≤ 1 := by + classical + by_cases h : ReadsBy π a V Z <;> simp [indicatorBy, h] + +theorem integrable_indicator (π : ScanRule) (a : ℕ) : Integrable (indicator π a) fairCoin := + (integrable_const (1 : ℝ)).indicator (measurableSet_reads π a) + +theorem integrable_indicatorBy (π : ScanRule) (a V : ℕ) : + Integrable (indicatorBy π a V) fairCoin := + (integrable_const (1 : ℝ)).indicator (measurableSet_readsBy π a V) + +theorem indicatorBy_le_indicator (π : ScanRule) (a V : ℕ) (Z : Cantor) : + indicatorBy π a V Z ≤ indicator π a Z := by + classical + by_cases h : ReadsBy π a V Z + · simp [indicatorBy, indicator, h, reads_of_readsBy h] + · simpa [indicatorBy, h] using (indicator_bounds π a Z).1 + +/-- For one position, the finite query indicator eventually equals its limit +on every prescribed answer sequence. -/ +theorem eventually_indicatorBy_eq (π : ScanRule) (a : ℕ) (Z : Cantor) : + ∀ᶠ V : ℕ in atTop, indicatorBy π a V Z = indicator π a Z := by + classical + by_cases h : Reads π a Z + · obtain ⟨t, ht⟩ := h + filter_upwards [eventually_ge_atTop (t + 1)] with V hV + have hb : ReadsBy π a V Z := ⟨t, by omega, ht⟩ + simp [indicatorBy, indicator, hb, reads_of_readsBy hb] + · filter_upwards [] with V + have hb : ¬ ReadsBy π a V Z := fun hb => h (reads_of_readsBy hb) + simp [indicatorBy, indicator, hb, h] + +/-- Fraction of the finite pool queried eventually. -/ +noncomputable def readFraction (π : ScanRule) (G : Finset ℕ) (Z : Cantor) : ℝ := + (∑ a ∈ G, indicator π a Z) / G.card + +/-- Fraction of the finite pool queried before the stated horizon. -/ +noncomputable def readFractionBy (π : ScanRule) (G : Finset ℕ) (V : ℕ) (Z : Cantor) : ℝ := + (∑ a ∈ G, indicatorBy π a V Z) / G.card + +theorem measurable_readFraction (π : ScanRule) (G : Finset ℕ) : + Measurable (readFraction π G) := by + exact (Finset.measurable_sum G fun a _ => measurable_indicator π a).div_const _ + +theorem measurable_readFractionBy (π : ScanRule) (G : Finset ℕ) (V : ℕ) : + Measurable (readFractionBy π G V) := by + exact (Finset.measurable_sum G fun a _ => measurable_indicatorBy π a V).div_const _ + +theorem readFraction_nonneg (π : ScanRule) (G : Finset ℕ) (Z : Cantor) : + 0 ≤ readFraction π G Z := + div_nonneg (Finset.sum_nonneg fun a _ => (indicator_bounds π a Z).1) (Nat.cast_nonneg _) + +theorem readFractionBy_nonneg (π : ScanRule) (G : Finset ℕ) (V : ℕ) (Z : Cantor) : + 0 ≤ readFractionBy π G V Z := + div_nonneg (Finset.sum_nonneg fun a _ => (indicatorBy_bounds π a V Z).1) (Nat.cast_nonneg _) + +theorem readFraction_le_one (π : ScanRule) (G : Finset ℕ) (Z : Cantor) : + readFraction π G Z ≤ 1 := by + by_cases hG : G.card = 0 + · simp [readFraction, hG] + · apply (div_le_iff₀ (by exact_mod_cast Nat.pos_of_ne_zero hG)).mpr + calc + (∑ a ∈ G, indicator π a Z) ≤ ∑ _a ∈ G, (1 : ℝ) := + Finset.sum_le_sum fun a _ => (indicator_bounds π a Z).2 + _ = _ := by simp + +theorem readFractionBy_le_readFraction (π : ScanRule) (G : Finset ℕ) (V : ℕ) (Z : Cantor) : + readFractionBy π G V Z ≤ readFraction π G Z := + div_le_div_of_nonneg_right + (Finset.sum_le_sum fun a _ => indicatorBy_le_indicator π a V Z) (Nat.cast_nonneg _) + +theorem integrable_readFraction (π : ScanRule) (G : Finset ℕ) : + Integrable (readFraction π G) fairCoin := + (integrable_finsetSum G fun a _ => integrable_indicator π a).div_const _ + +theorem integrable_readFractionBy (π : ScanRule) (G : Finset ℕ) (V : ℕ) : + Integrable (readFractionBy π G V) fairCoin := + (integrable_finsetSum G fun a _ => integrable_indicatorBy π a V).div_const _ + +/-- Every finite pool has a path-dependent horizon capturing all positions +that will ever be queried on that path. -/ +theorem eventually_readFractionBy_eq (π : ScanRule) (G : Finset ℕ) (Z : Cantor) : + ∀ᶠ V : ℕ in atTop, readFractionBy π G V Z = readFraction π G Z := by + have h := (eventually_all_finset G).mpr (fun a _ => eventually_indicatorBy_eq π a Z) + filter_upwards [h] with V hV + exact congrArg (fun s : ℝ => s / G.card) (Finset.sum_congr rfl hV) + +/-- The finite-horizon coverage fractions converge in the actual L¹ norm. -/ +theorem tendsto_readFractionBy_l1 (π : ScanRule) (G : Finset ℕ) : + Tendsto (fun V : ℕ => ∫ Z, |readFraction π G Z - readFractionBy π G V Z| ∂fairCoin) + atTop (𝓝 0) := by + have h := tendsto_integral_of_dominated_convergence (μ := fairCoin) + (F := fun V Z => |readFraction π G Z - readFractionBy π G V Z|) + (f := fun _ => (0 : ℝ)) (fun _ => (1 : ℝ)) + (fun V => by + simpa only [Real.norm_eq_abs, Pi.sub_apply] using ((measurable_readFraction π G).sub + (measurable_readFractionBy π G V)).norm.aestronglyMeasurable) + (integrable_const 1) (fun V => Filter.Eventually.of_forall fun Z => by + rw [Real.norm_eq_abs, abs_abs, abs_of_nonneg + (sub_nonneg.mpr (readFractionBy_le_readFraction π G V Z))] + linarith [readFraction_le_one π G Z, readFractionBy_nonneg π G V Z]) + (Filter.Eventually.of_forall fun Z => by + apply tendsto_const_nhds.congr' + filter_upwards [eventually_readFractionBy_eq π G Z] with V hV + simp [hV]) + simpa using h + +end Klr.PoolQuery diff --git a/LeanPool/KLRandomness/PoolQueryLimit.lean b/LeanPool/KLRandomness/PoolQueryLimit.lean new file mode 100644 index 0000000000..97cb54e812 --- /dev/null +++ b/LeanPool/KLRandomness/PoolQueryLimit.lean @@ -0,0 +1,205 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.PoolPartitionQuery +public import Mathlib.MeasureTheory.Function.LpSeminorm.CompareExp +import Mathlib.Tactic.Linarith +import Mathlib.Tactic.NormNum + +/-! +# Finite pools and finite-horizon limits + +The Hilbert-space average of the query indicators represents the actual +fraction of a finite pool that is eventually queried. Its distance to the +fixed weak limit bounds the corresponding L1 error. A union bound controls +the high-set mass on which a nonempty pool is not completely queried. + +For each fixed pool, the finite-horizon high missed mass and the expected +read fraction converge to their eventual counterparts. These are actual +query events and supply the analytic limits needed by the finite search. +-/ + +@[expose] public section + +noncomputable section + +namespace Klr.Pool + +open MeasureTheory Filter +open scoped ENNReal Topology BigOperators + +/-- The Hilbert-space average of the actual eventual-query indicators. -/ +def averageL2 (π : ScanRule) (G : Finset ℕ) : Lp ℝ 2 fairCoin := + (G.card : ℝ)⁻¹ • ∑ a ∈ G, queryL2 π a + +theorem averageL2_coeFn (π : ScanRule) (G : Finset ℕ) : + averageL2 π G =ᵐ[fairCoin] PoolQuery.readFraction π G := by + have hsum := Lp.coeFn_finsetSum G (queryL2 π) + have hind := (eventually_all_finset G).mpr (fun a _ => queryL2_coeFn π a) + filter_upwards [Lp.coeFn_smul (G.card : ℝ)⁻¹ (∑ a ∈ G, queryL2 π a), hsum, hind] + with Z hsmul hsum hind + change ((G.card : ℝ)⁻¹ • ∑ a ∈ G, queryL2 π a) Z = _ + rw [hsmul] + simp only [Pi.smul_apply, smul_eq_mul, hsum, Finset.sum_apply] + rw [Finset.sum_congr rfl hind] + simp only [PoolQuery.readFraction, div_eq_mul_inv, mul_comm] + +/-- On a probability space, the L1 norm is bounded by the L2 norm. -/ +theorem integral_norm_le_L2_norm (f : Lp ℝ 2 fairCoin) : + (∫ Z, ‖f Z‖ ∂fairCoin) ≤ ‖f‖ := by + rw [integral_norm_eq_lintegral_eNorm (Lp.aestronglyMeasurable f), + ← eLpNorm_one_eq_lintegral_eNorm (Lp.aestronglyMeasurable f), Lp.norm_def] + exact ENNReal.toReal_mono (Lp.eLpNorm_ne_top f) + (eLpNorm_le_eLpNorm_of_exponent_le (by norm_num : (1 : ℝ≥0∞) ≤ 2)) + +namespace QueryPartition + +/-- Hilbert-space approximation of a pool gives L1 approximation to the fixed +everywhere bounded Borel representative. -/ +theorem integral_abs_readFraction_sub_representative_le + {π : ℕ → ScanRule} {a : ℕ → ℕ} (D : QueryPartition π a) + (i : ℕ) (G : Finset ℕ) : + (∫ Z, |PoolQuery.readFraction (π i) G Z - D.representative i Z| ∂fairCoin) ≤ + ‖averageL2 (π i) G - D.limit i‖ := by + calc + _ = ∫ Z, ‖(averageL2 (π i) G - D.limit i) Z‖ ∂fairCoin := by + apply integral_congr_ae + filter_upwards [averageL2_coeFn (π i) G, D.representative_ae_eq i, + Lp.coeFn_sub (averageL2 (π i) G) (D.limit i)] with Z hav hrep hsub + simp only [Pi.sub_apply] at hsub + rw [hsub, hav, hrep, Real.norm_eq_abs] + _ ≤ _ := integral_norm_le_L2_norm _ + +end QueryPartition + +end Klr.Pool + +namespace Klr.PoolQuery + +open MeasureTheory Filter +open scoped Topology BigOperators symmDiff + +/-- If all members of a nonempty pool are eventually queried, its eventual +read fraction is one. -/ +theorem readFraction_eq_one_of_forall_reads (π : ScanRule) {G : Finset ℕ} + (hG : G.Nonempty) {Z : Cantor} (hreads : ∀ a ∈ G, Reads π a Z) : + readFraction π G Z = 1 := by + classical + have hs : ∑ a ∈ G, indicator π a Z = (G.card : ℝ) := by + calc + _ = ∑ _a ∈ G, (1 : ℝ) := by + apply Finset.sum_congr rfl + intro a ha + simp [indicator, hreads a ha] + _ = _ := by simp + rw [readFraction, hs] + exact div_self (by exact_mod_cast hG.card_ne_zero) + +/-- The high-set mass missing any member of a nonempty pool is bounded by +the sum of its individual missed masses. -/ +theorem high_miss_le_sum (π : ScanRule) {G : Finset ℕ} (hG : G.Nonempty) + (H : Set Cantor) : + fairCoin.real {Z | Z ∈ H ∧ readFraction π G Z < 1} ≤ + ∑ a ∈ G, fairCoin.real (H \ {Z | Reads π a Z}) := by + have hsub : {Z | Z ∈ H ∧ readFraction π G Z < 1} ⊆ + ⋃ a ∈ G, H \ {Z | Reads π a Z} := by + intro Z hZ + by_contra hnot + have hall : ∀ a ∈ G, Reads π a Z := by + intro a ha + by_contra hmiss + exact hnot (Set.mem_iUnion.mpr ⟨a, Set.mem_iUnion.mpr ⟨ha, hZ.1, hmiss⟩⟩) + have hone := readFraction_eq_one_of_forall_reads π hG hall + exact (ne_of_lt hZ.2) hone + exact (measureReal_mono hsub (measure_ne_top fairCoin _)).trans + (measureReal_biUnion_finset_le G _) + +/-- Replacing the fixed high set by a finite-prefix approximation costs only +its symmetric-difference error. -/ +theorem high_miss_le_sum_add_symmDiff (π : ScanRule) {G : Finset ℕ} + (hG : G.Nonempty) (H H' : Set Cantor) : + fairCoin.real {Z | Z ∈ H' ∧ readFraction π G Z < 1} ≤ + (∑ a ∈ G, fairCoin.real (H \ {Z | Reads π a Z})) + fairCoin.real (H' ∆ H) := by + have hsub : {Z | Z ∈ H' ∧ readFraction π G Z < 1} ⊆ + {Z | Z ∈ H ∧ readFraction π G Z < 1} ∪ (H' ∆ H) := by + intro Z hZ + by_cases hz : Z ∈ H + · exact Or.inl ⟨hz, hZ.2⟩ + · exact Or.inr (Set.mem_symmDiff.mpr (Or.inl ⟨hZ.1, hz⟩)) + calc + _ ≤ fairCoin.real ({Z | Z ∈ H ∧ readFraction π G Z < 1} ∪ (H' ∆ H)) := + measureReal_mono hsub (measure_ne_top fairCoin _) + _ ≤ fairCoin.real {Z | Z ∈ H ∧ readFraction π G Z < 1} + fairCoin.real (H' ∆ H) := + measureReal_union_le _ _ + _ ≤ _ := by linarith [high_miss_le_sum π hG H] + +/-- The actual finite-time high missed mass converges to the eventual high +missed mass of the same fixed pool. -/ +theorem tendsto_high_missBy (π : ScanRule) (G : Finset ℕ) + {H : Set Cantor} (hH : MeasurableSet H) : + Tendsto + (fun V : ℕ => fairCoin.real {Z | Z ∈ H ∧ readFractionBy π G V Z < 1}) + atTop (𝓝 (fairCoin.real {Z | Z ∈ H ∧ readFraction π G Z < 1})) := by + classical + let S (V : ℕ) : Set Cantor := {Z | Z ∈ H ∧ readFractionBy π G V Z < 1} + let T : Set Cantor := {Z | Z ∈ H ∧ readFraction π G Z < 1} + have hS (V : ℕ) : MeasurableSet (S V) := + hH.inter (measurableSet_lt (measurable_readFractionBy π G V) measurable_const) + have hT : MeasurableSet T := + hH.inter (measurableSet_lt (measurable_readFraction π G) measurable_const) + have h := tendsto_integral_of_dominated_convergence (μ := fairCoin) + (F := fun V => (S V).indicator (fun _ => (1 : ℝ))) + (f := T.indicator (fun _ => (1 : ℝ))) (fun _ => (1 : ℝ)) + (fun V => (measurable_const.indicator (hS V)).aestronglyMeasurable) + (integrable_const 1) (fun V => Filter.Eventually.of_forall fun Z => by + by_cases hz : Z ∈ S V <;> simp [Set.indicator, hz]) + (Filter.Eventually.of_forall fun Z => by + apply tendsto_const_nhds.congr' + filter_upwards [eventually_readFractionBy_eq π G Z] with V hV + simp only [S, T, Set.indicator, Set.mem_ofPred, hV]) + have hSI (V : ℕ) : (∫ Z, (S V).indicator (fun _ => (1 : ℝ)) Z ∂fairCoin) = + fairCoin.real (S V) := by + simpa using integral_indicator_const (μ := fairCoin) (1 : ℝ) (hS V) + have hTI : (∫ Z, T.indicator (fun _ => (1 : ℝ)) Z ∂fairCoin) = + fairCoin.real T := by + simpa using integral_indicator_const (μ := fairCoin) (1 : ℝ) hT + simpa only [hSI, hTI] using h + +/-- Expected finite-time query fractions converge to the expected eventual +fraction for every fixed finite pool. -/ +theorem tendsto_integral_readFractionBy (π : ScanRule) (G : Finset ℕ) : + Tendsto (fun V : ℕ => ∫ Z, readFractionBy π G V Z ∂fairCoin) + atTop (𝓝 (∫ Z, readFraction π G Z ∂fairCoin)) := by + apply tendsto_integral_of_dominated_convergence (fun _ => (1 : ℝ)) + (fun V => (measurable_readFractionBy π G V).aestronglyMeasurable) (integrable_const 1) + · intro V + exact Filter.Eventually.of_forall fun Z => by + rw [Real.norm_eq_abs, abs_of_nonneg (readFractionBy_nonneg π G V Z)] + exact (readFractionBy_le_readFraction π G V Z).trans (readFraction_le_one π G Z) + · apply Filter.Eventually.of_forall + intro Z + apply tendsto_const_nhds.congr' + filter_upwards [eventually_readFractionBy_eq π G Z] with V hV + exact hV.symm + +/-- Expected eventual coverage is the average of the individual query +probabilities. -/ +theorem integral_readFraction (π : ScanRule) (G : Finset ℕ) : + (∫ Z, readFraction π G Z ∂fairCoin) = + (∑ a ∈ G, fairCoin.real {Z | Reads π a Z}) / G.card := by + unfold readFraction + rw [integral_div, integral_finsetSum G (fun a _ => integrable_indicator π a)] + congr 1 + apply Finset.sum_congr rfl + intro a _ + simpa only [indicator, smul_eq_mul, mul_one] using + integral_indicator_const (μ := fairCoin) (1 : ℝ) (measurableSet_reads π a) + +end Klr.PoolQuery diff --git a/LeanPool/KLRandomness/PoolSearch.lean b/LeanPool/KLRandomness/PoolSearch.lean new file mode 100644 index 0000000000..486e6dd890 --- /dev/null +++ b/LeanPool/KLRandomness/PoolSearch.lean @@ -0,0 +1,223 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.PoolAdviceComputable +public import Mathlib.Computability.PartrecCode +import Mathlib.Tactic.Tauto + +/-! +# The fixed-advice pool-producing program + +For each fixed finite family of scans and each fixed finite advice record, +there is a single partial-recursive program taking only the requested pool +size M. It enumerates pairs consisting of a finite pool and a finite horizon, +and returns the first pair passing all three exact rational tests. + +The equivalence between halting and existence of an accepted candidate is +unconditional. The analytic argument must separately establish that accepted +candidates exist for sufficiently large M; that condition is not built into +the computation as an oracle or a computability assumption. +-/ + +@[expose] public section + +namespace Klr.PoolAdvice + +open SparseSearch SparseListSearch RationalComputability + +/-- A bounded duplicate test, checking that every listed value occurs once. -/ +def nodupCheck (G : List ℕ) : Bool := + G.all fun a => decide (G.countP (fun b => decide (b = a)) = 1) + +theorem nodupCheck_eq_true (G : List ℕ) : nodupCheck G = true ↔ G.Nodup := by + simpa only [nodupCheck, List.all_eq_true, decide_eq_true_eq, List.count, + Bool.beq_eq_decide_eq] using (List.nodup_iff_count_eq_one (l := G)).symm + +theorem computable_nodupCheck : Computable nodupCheck := by + have he : Computable (fun p : (List ℕ × ℕ) × ℕ => decide (p.2 = p.1.2)) := + Primrec.eq.decide.to_comp.comp Computable.snd (Computable.snd.comp Computable.fst) + have hc := computable_list_countP (p := fun p : List ℕ × ℕ => fun b => decide (b = p.2)) + Computable.fst he + have hb := Primrec.eq.decide.to_comp.comp hc (Computable.const 1) + exact computable_list_all + (p := fun (G : List ℕ) (a : ℕ) => decide (G.countP (fun b => decide (b = a)) = 1)) + Computable.id hb + +/-- The exact finite verifier for an M-element pool and a finite horizon. -/ +def check (rules : List ScanRule) (A : Advice) (M : ℕ) (C : Candidate) : Bool := + decide (C.1.length = M) && nodupCheck C.1 && + C.1.all (fun a => decide (A.positionBound ≤ a)) && + EffectiveScan.boundedAll (fun i => decide (highMiss rules A C.1 C.2 i < 3 * A.error)) + A.protectedCount && + EffectiveScan.boundedAll (fun i => decide (distance rules A C.1 C.2 i < 3 * A.error)) + A.protectedCount && + decide (A.threshold < weightedMass rules A C.1 C.2) + +theorem check_eq_true (rules : List ScanRule) (A : Advice) (M : ℕ) (C : Candidate) : + check rules A M C = true ↔ Accepted rules A M C := by + simp only [check, Bool.and_eq_true, decide_eq_true_eq, nodupCheck_eq_true, + List.all_eq_true, EffectiveScan.boundedAll_eq_true, Accepted] + tauto + +/-- The scans and advice are constants of this total computable verifier. -/ +theorem computable_check (rules : List ScanRule) (A : Advice) : + Computable₂ (check rules A) := by + have hG : Computable (fun p : ℕ × Candidate => p.2.1) := + Computable.fst.comp Computable.snd + have hs := Primrec.eq.decide.to_comp.comp (Computable.list_length.comp hG) Computable.fst + have hd := computable_nodupCheck.comp hG + have hb := computable_list_all (p := fun (_ : ℕ × Candidate) a => decide (A.positionBound ≤ a)) + hG (Primrec.nat_le.decide.to_comp.comp (Computable.const A.positionBound) Computable.snd) + have hpair : Computable (fun p : (ℕ × Candidate) × ℕ => (p.1.2, p.2)) := + (Computable.snd.comp Computable.fst).pair Computable.snd + have hh := computable_rat_lt.comp ((computable_highMiss rules A).comp hpair) + (Computable.const (3 * A.error)) + have hl := computable_rat_lt.comp ((computable_distance rules A).comp hpair) + (Computable.const (3 * A.error)) + have hhigh := (EffectiveScan.computable_boundedAll + (p := fun p : ℕ × Candidate => fun i => decide (highMiss rules A p.2.1 p.2.2 i < 3 * A.error)) + hh).comp (Computable.id.pair (Computable.const A.protectedCount)) + have hlow := (EffectiveScan.computable_boundedAll + (p := fun p : ℕ × Candidate => fun i => decide (distance rules A p.2.1 p.2.2 i < 3 * A.error)) + hl).comp (Computable.id.pair (Computable.const A.protectedCount)) + have hm : Computable (fun p : ℕ × Candidate => + decide (A.threshold < weightedMass rules A p.2.1 p.2.2)) := + computable_rat_lt.comp (Computable.const A.threshold) + ((computable_weightedMass rules A).comp Computable.snd) + exact Primrec.and.to_comp.comp + (Primrec.and.to_comp.comp (Primrec.and.to_comp.comp + (Primrec.and.to_comp.comp (Primrec.and.to_comp.comp hs hd) hb) hhigh) hlow) hm + +/-- Use the canonical primitive coding of a candidate throughout the search. -/ +def encodeCandidate (C : Candidate) : ℕ := + @Encodable.encode Candidate (inferInstance : Primcodable Candidate).toEncodable C + +/-- Decode one ordinary natural-number candidate and run the finite verifier. -/ +def trial (rules : List ScanRule) (A : Advice) (M n : ℕ) : Option Candidate := + (@Encodable.decode Candidate (inferInstance : Primcodable Candidate).toEncodable n).bind + fun C => if check rules A M C then some C else none + +theorem computable_trial (rules : List ScanRule) (A : Advice) : + Computable₂ (trial rules A) := by + have hf : Computable₂ (fun M C => if check rules A M C then some C else none) := by + have h := Computable.cond (computable_check rules A) + (Computable.option_some.comp Computable.snd) (Computable.const none) + exact h.of_eq fun _ => by simp [Bool.cond_eq_ite] + exact Computable.bind_decode_iff.mpr hf + +/-- The actual fixed-advice exhaustive search, whose only input is M. -/ +def search (rules : List ScanRule) (A : Advice) (M : ℕ) : Part Candidate := + Nat.rfindOpt (trial rules A M) + +theorem partrec_search (rules : List ScanRule) (A : Advice) : + Partrec (search rules A) := Partrec.rfindOpt (computable_trial rules A) + +theorem search_check {rules : List ScanRule} {A : Advice} {M : ℕ} {C : Candidate} + (hC : C ∈ search rules A M) : check rules A M C = true := by + obtain ⟨n, hn⟩ := Nat.rfindOpt_spec hC + simp only [trial, Option.mem_bind_iff] at hn + obtain ⟨B, _, hB⟩ := hn + split_ifs at hB with hv + · have he : B = C := Option.mem_some_iff.mp hB + simpa only [he] using hv + · simp at hB + +theorem search_spec {rules : List ScanRule} {A : Advice} {M : ℕ} {C : Candidate} + (hC : C ∈ search rules A M) : Accepted rules A M C := + (check_eq_true rules A M C).mp (search_check hC) + +/-- Analytic finite existence is exactly what is needed to prove halting. -/ +theorem search_dom_iff (rules : List ScanRule) (A : Advice) (M : ℕ) : + (search rules A M).Dom ↔ ∃ C, Accepted rules A M C := by + constructor + · intro h + obtain ⟨C, hC⟩ := Part.dom_iff_mem.mp h + exact ⟨C, search_spec hC⟩ + · rintro ⟨C, hC⟩ + apply Nat.rfindOpt_dom.mpr + refine ⟨encodeCandidate C, C, ?_⟩ + simp only [trial, encodeCandidate, Encodable.encodek, Option.bind_some] + rw [(check_eq_true rules A M C).mpr hC] + exact Option.mem_some_self C + +/-- One fixed program handles every requested M. All non-effective choices +are in the finite list of scans and the finite advice record before ∀M. -/ +theorem exists_search_program (rules : List ScanRule) (A : Advice) : + ∃ e : Nat.Partrec.Code, ∀ M : ℕ, + e.eval M = (search rules A M).map encodeCandidate := by + obtain ⟨e, he⟩ := Nat.Partrec.Code.exists_code.mp (partrec_search rules A) + refine ⟨e, fun M => ?_⟩ + rw [he] + simp only [Encodable.decode_nat, Part.coe_some, Part.bind_some] + rfl + +/-- When the analytic existence theorem is supplied, the same program halts +on every sufficiently large input and every output satisfies all finite tests. -/ +theorem exists_eventually_halting_program (rules : List ScanRule) (A : Advice) + (h : ∀ᶠ M in Filter.atTop, ∃ C, Accepted rules A M C) : + ∃ e : Nat.Partrec.Code, + (∀ M, e.eval M = (search rules A M).map encodeCandidate) ∧ + ∀ᶠ M in Filter.atTop, (e.eval M).Dom := by + obtain ⟨e, he⟩ := exists_search_program rules A + refine ⟨e, he, ?_⟩ + filter_upwards [h] with M hM + rw [he] + exact (search_dom_iff rules A M).mpr hM + +/-- The pool-producing partial function forgets the search horizon. -/ +def pool (rules : List ScanRule) (A : Advice) (M : ℕ) : Part (List ℕ) := + (search rules A M).map Prod.fst + +theorem partrec_pool (rules : List ScanRule) (A : Advice) : + Partrec (pool rules A) := + (partrec_search rules A).map (Computable.fst.comp Computable.snd) + +/-- Every pool returned by the program has a horizon witnessing all three tests. -/ +theorem pool_spec {rules : List ScanRule} {A : Advice} {M : ℕ} {G : List ℕ} + (hG : G ∈ pool rules A M) : ∃ V, Accepted rules A M (G, V) := by + obtain ⟨C, hC, hCG⟩ := (Part.mem_map_iff Prod.fst).mp hG + exact ⟨C.2, hCG ▸ search_spec hC⟩ + +theorem pool_dom_iff (rules : List ScanRule) (A : Advice) (M : ℕ) : + (pool rules A M).Dom ↔ ∃ G V, Accepted rules A M (G, V) := by + change (search rules A M).Dom ↔ _ + rw [search_dom_iff] + exact ⟨fun ⟨⟨G, V⟩, h⟩ => ⟨G, V, h⟩, fun ⟨G, V, h⟩ => ⟨(G, V), h⟩⟩ + +/-- The output encoding is the canonical computability presentation of lists. -/ +def encodePool (G : List ℕ) : ℕ := + @Encodable.encode (List ℕ) (inferInstance : Primcodable (List ℕ)).toEncodable G + +/-- A single program returns a finite pool from its requested size; the finite +advice, the scans, and the compiler are all fixed outside the input quantifier. -/ +theorem exists_pool_program (rules : List ScanRule) (A : Advice) : + ∃ e : Nat.Partrec.Code, ∀ M : ℕ, + e.eval M = (pool rules A M).map encodePool := by + obtain ⟨e, he⟩ := Nat.Partrec.Code.exists_code.mp (partrec_pool rules A) + refine ⟨e, fun M => ?_⟩ + rw [he] + simp only [Encodable.decode_nat, Part.coe_some, Part.bind_some] + rfl + +/-- Once accepted candidates exist eventually, one fixed program eventually +returns pools satisfying the finite acceptance specification. -/ +theorem exists_eventual_pool_program (rules : List ScanRule) (A : Advice) + (h : ∀ᶠ M in Filter.atTop, ∃ C, Accepted rules A M C) : + ∃ e : Nat.Partrec.Code, ∀ᶠ M in Filter.atTop, + ∃ G V, encodePool G ∈ e.eval M ∧ Accepted rules A M (G, V) := by + obtain ⟨e, he⟩ := exists_pool_program rules A + refine ⟨e, ?_⟩ + filter_upwards [h] with M hM + obtain ⟨C, hC⟩ := Part.dom_iff_mem.mp ((search_dom_iff rules A M).mpr hM) + refine ⟨C.1, C.2, ?_, search_spec hC⟩ + rw [he] + exact Part.mem_map encodePool (Part.mem_map Prod.fst hC) + +end Klr.PoolAdvice diff --git a/LeanPool/KLRandomness/PoolSelection.lean b/LeanPool/KLRandomness/PoolSelection.lean new file mode 100644 index 0000000000..33ac5b291f --- /dev/null +++ b/LeanPool/KLRandomness/PoolSelection.lean @@ -0,0 +1,176 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.PoolWeakLimit +public import Mathlib.Analysis.SpecificLimits.Basic +import Mathlib.Tactic.FieldSimp +import Mathlib.Tactic.Linarith +import Mathlib.Tactic.Positivity +import Mathlib.Tactic.Ring + +/-! +# Finite selection from common weak limits + +For every requested finite size, weak convergence permits a set of samples +with arbitrarily small pairwise centered inner products. Finitely many +eventual side conditions may be imposed at the same time, and the selected +positions can be made distinct. The squared norm of their average is bounded +by `4 / M + ε` when the samples and their limits lie in the unit ball. + +This is the finite selection used to prove termination of the pool search. +It does not require an effective modulus of weak convergence. +-/ + +@[expose] public section + +namespace Klr.Pool + +open Filter +open scoped Topology BigOperators + +variable {E : Type*} [NormedAddCommGroup E] [InnerProductSpace ℝ E] + +/-- Weak convergence supplies arbitrarily large finite sets of nearly +orthogonal centered vectors, with all eventual side conditions retained. -/ +theorem exists_finite_weak_samples (u : ℕ → ℕ → E) (g : ℕ → E) + (hu : ∀ i, WeaklyConverges (u i) (g i)) + (a : ℕ → ℕ) (ha : Tendsto a atTop atTop) + (P : ℕ → Prop) (hP : ∀ᶠ n in atTop, P n) (ℓ : ℕ) + {ε : ℝ} (hε : 0 < ε) (M : ℕ) : + ∃ F : Finset ℕ, F.card = M ∧ + (∀ n ∈ F, P n) ∧ Set.InjOn a F ∧ + ∀ i < ℓ, ∀ n ∈ F, ∀ m ∈ F, n ≠ m → + inner ℝ (u i n - g i) (u i m - g i) < ε := by + classical + induction M with + | zero => exact ⟨∅, by simp, by simp, by simp, by simp⟩ + | succ M ih => + obtain ⟨F, hcard, hPF, hAF, hcrossF⟩ := ih + have hcross : ∀ᶠ k : ℕ in atTop, + ∀ i : Fin ℓ, ∀ m ∈ F, + inner ℝ (u i k - g i) (u i m - g i) < ε := by + apply Filter.eventually_all.mpr + intro i + apply (Filter.eventually_all_finset F).mpr + intro m hm + have ht : Tendsto (fun k => inner ℝ (u i k - g i) (u i m - g i)) + atTop (𝓝 0) := by + simpa only [inner_sub_left, sub_self] using + (hu i (u i m - g i)).sub + (tendsto_const_nhds (x := inner ℝ (g i) (u i m - g i))) + exact ht.eventually (gt_mem_nhds hε) + have hlarge : ∀ᶠ k : ℕ in atTop, F.sup a < a k := + ha.eventually (eventually_gt_atTop (F.sup a)) + obtain ⟨k, hPk, hk, hC⟩ := (hP.and (hlarge.and hcross)).exists + have hbig : ∀ n ∈ F, a n < a k := fun n hn => + lt_of_le_of_lt (Finset.le_sup (f := a) hn) hk + have hkF : k ∉ F := fun hkF => (lt_irrefl (a k)) (hbig k hkF) + refine ⟨insert k F, by simp [hkF, hcard], ?_, ?_, ?_⟩ + · intro n hn + rcases Finset.mem_insert.mp hn with rfl | hn + · exact hPk + · exact hPF n hn + · intro n hn m hm he + by_cases hnk : n = k + · subst n + by_cases hmk : m = k + · exact hmk.symm + · have hmF := (Finset.mem_insert.mp hm).resolve_left hmk + exact False.elim ((ne_of_lt (hbig m hmF)) he.symm) + · have hnF := (Finset.mem_insert.mp hn).resolve_left hnk + by_cases hmk : m = k + · subst m + exact False.elim ((ne_of_lt (hbig n hnF)) he) + · exact hAF hnF ((Finset.mem_insert.mp hm).resolve_left hmk) he + · intro i hi n hn m hm hne + by_cases hnk : n = k + · subst n + have hmF := (Finset.mem_insert.mp hm).resolve_left (Ne.symm hne) + exact hC ⟨i, hi⟩ m hmF + · have hnF := (Finset.mem_insert.mp hn).resolve_left hnk + by_cases hmk : m = k + · subst m + rw [real_inner_comm] + exact hC ⟨i, hi⟩ n hnF + · exact hcrossF i hi n hnF m ((Finset.mem_insert.mp hm).resolve_left hmk) hne + +/-- The diagonal contributes at most `4 M`; the off-diagonal terms contribute +at most `ε M²`. The slightly generous constant avoids special indicator algebra. -/ +theorem norm_sum_sq_le_of_inner_le (v : ℕ → E) (F : Finset ℕ) {ε : ℝ} + (hε : 0 ≤ ε) (hv : ∀ n ∈ F, ‖v n‖ ≤ 2) + (hcross : ∀ n ∈ F, ∀ m ∈ F, n ≠ m → inner ℝ (v n) (v m) ≤ ε) : + ‖∑ n ∈ F, v n‖ ^ 2 ≤ 4 * (F.card : ℝ) + ε * (F.card : ℝ) ^ 2 := by + classical + rw [← real_inner_self_eq_norm_sq, sum_inner] + simp_rw [inner_sum] + calc + _ ≤ ∑ n ∈ F, ∑ m ∈ F, ((if n = m then (4 : ℝ) else 0) + ε) := by + apply Finset.sum_le_sum + intro n hn + apply Finset.sum_le_sum + intro m hm + by_cases hnm : n = m + · subst m + simp only [↓reduceIte, real_inner_self_eq_norm_sq] + have h := hv n hn + nlinarith [norm_nonneg (v n)] + · simpa [hnm] using hcross n hn m hm hnm + _ = _ := by + simp [Finset.sum_add_distrib, Finset.sum_ite_eq, pow_two] + ring + +/-- Quantitative average estimate used in the finite pool witness. -/ +theorem norm_average_sq_le_of_inner_le (v : ℕ → E) (F : Finset ℕ) + (hF : F.Nonempty) {ε : ℝ} (hε : 0 ≤ ε) (hv : ∀ n ∈ F, ‖v n‖ ≤ 2) + (hcross : ∀ n ∈ F, ∀ m ∈ F, n ≠ m → inner ℝ (v n) (v m) ≤ ε) : + ‖(F.card : ℝ)⁻¹ • ∑ n ∈ F, v n‖ ^ 2 ≤ 4 / (F.card : ℝ) + ε := by + have hcard : (0 : ℝ) < F.card := by exact_mod_cast hF.card_pos + rw [norm_smul, Real.norm_eq_abs, abs_of_pos (inv_pos.mpr hcard), mul_pow] + calc + _ ≤ (F.card : ℝ)⁻¹ ^ 2 * (4 * (F.card : ℝ) + ε * (F.card : ℝ) ^ 2) := + mul_le_mul_of_nonneg_left (norm_sum_sq_le_of_inner_le v F hε hv hcross) (sq_nonneg _) + _ = _ := by field_simp + +/-- For all sufficiently large requested sizes, a finite weak sample has a +small centered average and satisfies every eventual side condition. -/ +theorem eventually_exists_finite_weak_average (u : ℕ → ℕ → E) (g : ℕ → E) + (hu : ∀ i, WeaklyConverges (u i) (g i)) + (hu1 : ∀ i n, ‖u i n‖ ≤ 1) (hg1 : ∀ i, ‖g i‖ ≤ 1) + (a : ℕ → ℕ) (ha : Tendsto a atTop atTop) (ℓ : ℕ) + {δ : ℝ} (hδ : 0 < δ) : + ∀ᶠ M : ℕ in atTop, ∀ (P : ℕ → Prop), (∀ᶠ n in atTop, P n) → + ∃ F : Finset ℕ, F.card = M ∧ (∀ n ∈ F, P n) ∧ Set.InjOn a F ∧ + ∀ i < ℓ, ‖(F.card : ℝ)⁻¹ • ∑ n ∈ F, (u i n - g i)‖ < δ := by + have hsmall : ∀ᶠ M : ℕ in atTop, 4 / (M : ℝ) + δ ^ 2 / 4 < δ ^ 2 := by + have ht : Tendsto (fun M : ℕ => 4 / (M : ℝ) + δ ^ 2 / 4) + atTop (𝓝 (δ ^ 2 / 4)) := by + simpa using ((tendsto_const_nhds (x := (4 : ℝ))).div_atTop + tendsto_natCast_atTop_atTop).add_const (δ ^ 2 / 4) + exact ht.eventually (gt_mem_nhds (by nlinarith [sq_pos_of_pos hδ])) + filter_upwards [eventually_ge_atTop 1, hsmall] with M hM hsmall + intro P hP + obtain ⟨F, hcard, hPF, hinj, hcross⟩ := exists_finite_weak_samples u g hu a ha P hP ℓ + (show 0 < δ ^ 2 / 4 by positivity) M + refine ⟨F, hcard, hPF, hinj, ?_⟩ + intro i hi + have hF : F.Nonempty := Finset.card_pos.mp (by omega) + have hnorm : ∀ n ∈ F, ‖u i n - g i‖ ≤ 2 := by + intro n _ + exact (norm_sub_le _ _).trans (by linarith [hu1 i n, hg1 i]) + have hbound := norm_average_sq_le_of_inner_le (fun n => u i n - g i) F hF + (show 0 ≤ δ ^ 2 / 4 by positivity) hnorm + (fun n hn m hm hne => (hcross i hi n hn m hm hne).le) + rw [hcard] at hbound + have hsq : ‖(F.card : ℝ)⁻¹ • ∑ n ∈ F, (u i n - g i)‖ ^ 2 < δ ^ 2 := by + rw [hcard] + exact hbound.trans_lt hsmall + nlinarith [norm_nonneg ((F.card : ℝ)⁻¹ • ∑ n ∈ F, (u i n - g i))] + +end Klr.Pool diff --git a/LeanPool/KLRandomness/PoolSoundness.lean b/LeanPool/KLRandomness/PoolSoundness.lean new file mode 100644 index 0000000000..991c5957a4 --- /dev/null +++ b/LeanPool/KLRandomness/PoolSoundness.lean @@ -0,0 +1,226 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.PoolAdviceMeasure +public import LeanPool.KLRandomness.PoolSearch +import Mathlib.Tactic.Linarith +import Mathlib.Tactic.NormNum +import Mathlib.Tactic.Positivity + +/-! +# Soundness of the fixed-advice pool tests + +Acceptance only controls a finite horizon. A global upper bound on the final +weighted mass bounds all later increases. The gap between this upper bound +and the accepted weighted mass gives the paper's `4δ` increment bound and +`8δ` L1 bound. Approximation of the high sets and Markov's inequality then +give the two measure estimates required of an output pool. + +All analytic hypotheses are explicit: this file does not assume a computable +limit, and it does not claim that the search terminates without a separate +finite-existence argument. +-/ + +@[expose] public section + +namespace Klr.PoolSoundness + +open MeasureTheory Filter +open scoped BigOperators symmDiff + +/-- A nonnegative weighted increment is controlled by the gap between a final +upper bound and a strict lower bound on the initial weighted mass. -/ +theorem increment_lt_of_weighted_gap {D i : ℕ} {w v u : ℕ → ℝ} + {B γ δ w₀ : ℝ} (hi : i < D) + (hw : ∀ j < D, 0 ≤ w j) (hmon : ∀ j < D, u j ≤ v j) + (hB : ∑ j ∈ Finset.range D, w j * v j ≤ B) + (hγ : γ < ∑ j ∈ Finset.range D, w j * u j) + (hgap : B - γ < 4 * w₀ * δ) (hw₀ : 0 < w₀) (hwi : w₀ ≤ w i) : + v i - u i < 4 * δ := by + have hsum : ∑ j ∈ Finset.range D, w j * (v j - u j) < B - γ := by + simp_rw [mul_sub] + rw [Finset.sum_sub_distrib] + linarith + have hterm : w i * (v i - u i) ≤ + ∑ j ∈ Finset.range D, w j * (v j - u j) := + Finset.single_le_sum (fun j hj => mul_nonneg (hw j (Finset.mem_range.mp hj)) + (sub_nonneg.mpr (hmon j (Finset.mem_range.mp hj)))) (Finset.mem_range.mpr hi) + have hleft : w₀ * (v i - u i) ≤ w i * (v i - u i) := + mul_le_mul_of_nonneg_right hwi (sub_nonneg.mpr (hmon i hi)) + have hlt := lt_of_le_of_lt hleft (lt_of_le_of_lt hterm (hsum.trans hgap)) + nlinarith + +/-- The L1 triangle inequality, stated directly for real integrals. -/ +theorem integral_abs_sub_le_add {f g h : Cantor → ℝ} + (hf : Integrable f fairCoin) (hg : Integrable g fairCoin) + (hh : Integrable h fairCoin) : + (∫ Z, |f Z - h Z| ∂fairCoin) ≤ + (∫ Z, |f Z - g Z| ∂fairCoin) + (∫ Z, |g Z - h Z| ∂fairCoin) := by + calc + (∫ Z, |f Z - h Z| ∂fairCoin) ≤ ∫ Z, |f Z - g Z| + |g Z - h Z| ∂fairCoin := + integral_mono (hf.sub hh).abs ((hf.sub hg).abs.add (hg.sub hh).abs) + (fun Z => abs_sub_le (f Z) (g Z) (h Z)) + _ = _ := by simpa only [Pi.sub_apply] using + integral_add (hf.sub hg).abs (hg.sub hh).abs + +/-- For monotone real coverage functions, the L1 increment is the difference +of their expected coverage. -/ +theorem integral_abs_sub_of_le {u v : Cantor → ℝ} + (hu : Integrable u fairCoin) (hv : Integrable v fairCoin) (h : ∀ Z, u Z ≤ v Z) : + (∫ Z, |v Z - u Z| ∂fairCoin) = (∫ Z, v Z ∂fairCoin) - ∫ Z, u Z ∂fairCoin := by + rw [← integral_sub hv hu] + apply integral_congr_ae + exact Eventually.of_forall fun Z => abs_of_nonneg (sub_nonneg.mpr (h Z)) + +/-- Set approximation transfers a high-set failure bound from finite coverage +to eventual coverage, using only their pointwise monotonicity. -/ +theorem high_failure_lt {H H' : Set Cantor} {u v : Cantor → ℝ} {δ : ℝ} + (hmon : ∀ Z, u Z ≤ v Z) (hH : fairCoin.real (H ∆ H') < δ) + (hu : fairCoin.real {Z | Z ∈ H' ∧ u Z < 1} < 3 * δ) : + fairCoin.real {Z | Z ∈ H ∧ v Z < 1} < 4 * δ := by + have hsub : {Z | Z ∈ H ∧ v Z < 1} ⊆ + (H ∆ H') ∪ {Z | Z ∈ H' ∧ u Z < 1} := by + intro Z hZ + by_cases hZ' : Z ∈ H' + · exact Or.inr ⟨hZ', lt_of_le_of_lt (hmon Z) hZ.2⟩ + · exact Or.inl (Or.inl ⟨hZ.1, hZ'⟩) + have hle := (measureReal_mono (μ := fairCoin) hsub).trans + (measureReal_union_le (μ := fairCoin) (H ∆ H') {Z | Z ∈ H' ∧ u Z < 1}) + linarith + +/-- An L1 error controls the low-set points on which coverage is nearly full. +The separate near-one margin is a property of the fixed limiting function. -/ +theorem low_near_full_le {v g : Cantor → ℝ} {τ : ℝ} + (hv : Integrable v fairCoin) (hg : Integrable g fairCoin) (hτ : 0 < τ) : + fairCoin.real {Z | g Z < 1 ∧ 1 - τ < v Z} ≤ + fairCoin.real {Z | 1 - 2 * τ < g Z ∧ g Z < 1} + + (∫ Z, |v Z - g Z| ∂fairCoin) / τ := by + have hsub : {Z | g Z < 1 ∧ 1 - τ < v Z} ⊆ + {Z | 1 - 2 * τ < g Z ∧ g Z < 1} ∪ {Z | τ ≤ |v Z - g Z|} := by + intro Z hZ + by_cases hm : 1 - 2 * τ < g Z + · exact Or.inl ⟨hm, hZ.1⟩ + · apply Or.inr + have hg' : g Z ≤ 1 - 2 * τ := le_of_not_gt hm + have hv' : 1 - τ < v Z := hZ.2 + have he : τ < v Z - g Z := by linarith + exact he.le.trans (le_abs_self _) + have hm := mul_meas_ge_le_integral_of_nonneg + (μ := fairCoin) (f := fun Z => |v Z - g Z|) + (Eventually.of_forall fun Z => abs_nonneg _) (hv.sub hg).abs τ + have hdiv : fairCoin.real {Z | τ ≤ |v Z - g Z|} ≤ + (∫ Z, |v Z - g Z| ∂fairCoin) / τ := by + apply (le_div_iff₀ hτ).mpr + simpa only [mul_comm] using hm + exact ((measureReal_mono (μ := fairCoin) hsub).trans + (measureReal_union_le (μ := fairCoin) _ _)).trans (add_le_add le_rfl hdiv) + +theorem low_near_full_lt {v g : Cantor → ℝ} {τ δ ε : ℝ} + (hv : Integrable v fairCoin) (hg : Integrable g fairCoin) (hτ : 0 < τ) + (herr : (∫ Z, |v Z - g Z| ∂fairCoin) < 8 * δ) + (hmargin : fairCoin.real {Z | 1 - 2 * τ < g Z ∧ g Z < 1} < ε) : + fairCoin.real {Z | g Z < 1 ∧ 1 - τ < v Z} < ε + 8 * δ / τ := by + exact (low_near_full_le hv hg hτ).trans_lt + (add_lt_add hmargin (div_lt_div_of_pos_right herr hτ)) + +end Klr.PoolSoundness + +namespace Klr.PoolAdvice + +open MeasureTheory Filter PoolQuery PoolSoundness +open scoped BigOperators symmDiff + +/-- The minimum weight among the protected zero-based indices. -/ +noncomputable def protectedWeight (A : Advice) : ℝ := (1 / 2 : ℝ) ^ A.protectedCount + +theorem protectedWeight_pos (A : Advice) : 0 < protectedWeight A := by + exact pow_pos (by norm_num) _ + +theorem protectedWeight_le_weight (A : Advice) {i : ℕ} (hi : i < A.protectedCount) : + protectedWeight A ≤ (weight i : ℝ) := by + simp only [protectedWeight, weight, Rat.cast_pow, Rat.cast_div, Rat.cast_one, Rat.cast_ofNat] + exact pow_le_pow_of_le_one (by norm_num) (by norm_num) (by omega) + +theorem weight_nonneg (i : ℕ) : (0 : ℝ) ≤ weight i := by + simp only [weight, Rat.cast_pow, Rat.cast_div, Rat.cast_one, Rat.cast_ofNat] + positivity + +/-- The accepted weighted mass bounds every protected scan's later L1 increase. -/ +theorem Accepted.later_increase_lt {rules : List ScanRule} {A : Advice} {M : ℕ} + {C : Candidate} (h : Accepted rules A M C) (π : ℕ → ScanRule) + (hπ : ∀ i < rules.length, rules[i]? = some (π i)) + (hℓ : A.protectedCount ≤ rules.length) {B : ℝ} + (hB : ∑ i ∈ Finset.range rules.length, + (weight i : ℝ) * ∫ Z, readFraction (π i) C.1.toFinset Z ∂fairCoin ≤ B) + (hgap : B - (A.threshold : ℝ) < 4 * protectedWeight A * (A.error : ℝ)) + {i : ℕ} (hi : i < A.protectedCount) : + (∫ Z, |readFraction (π i) C.1.toFinset Z - + readFractionBy (π i) C.1.toFinset C.2 Z| ∂fairCoin) < 4 * (A.error : ℝ) := by + rw [integral_abs_sub_of_le (integrable_readFractionBy _ _ _) + (integrable_readFraction _ _) (readFractionBy_le_readFraction _ _ _)] + exact increment_lt_of_weighted_gap (hi.trans_le hℓ) + (fun j _ => weight_nonneg j) + (fun j _ => integral_mono (integrable_readFractionBy _ _ _) (integrable_readFraction _ _) + (readFractionBy_le_readFraction _ _ _)) + hB (h.measure_spec π hπ hℓ).2.2 hgap (protectedWeight_pos A) + (protectedWeight_le_weight A hi) + +/-- Finite acceptance, later-increase control, and fixed cylinder approximation +give the paper's strict `8δ` L1 bound for final coverage. -/ +theorem Accepted.final_l1_lt {rules : List ScanRule} {A : Advice} {M : ℕ} + {C : Candidate} (h : Accepted rules A M C) (π : ℕ → ScanRule) + (hπ : ∀ i < rules.length, rules[i]? = some (π i)) + (hℓ : A.protectedCount ≤ rules.length) {B : ℝ} + (hB : ∑ i ∈ Finset.range rules.length, + (weight i : ℝ) * ∫ Z, readFraction (π i) C.1.toFinset Z ∂fairCoin ≤ B) + (hgap : B - (A.threshold : ℝ) < 4 * protectedWeight A * (A.error : ℝ)) + {i : ℕ} (hi : i < A.protectedCount) {g : Cantor → ℝ} + (hg : Integrable g fairCoin) + (happrox : (∫ Z, |approx A i Z - g Z| ∂fairCoin) < (A.error : ℝ)) : + (∫ Z, |readFraction (π i) C.1.toFinset Z - g Z| ∂fairCoin) < 8 * (A.error : ℝ) := by + have h₁ := h.later_increase_lt π hπ hℓ hB hgap hi + have h₂ := (h.measure_spec π hπ hℓ).2.1 i hi + have htriangle₁ := integral_abs_sub_le_add (integrable_readFraction (π i) C.1.toFinset) + (integrable_readFractionBy (π i) C.1.toFinset C.2) hg + have htriangle₂ := integral_abs_sub_le_add + (integrable_readFractionBy (π i) C.1.toFinset C.2) (integrable_approx A i) hg + linarith + +/-- The accepted finite high-set test controls eventual high-set failure. -/ +theorem Accepted.high_failure_lt {rules : List ScanRule} {A : Advice} {M : ℕ} + {C : Candidate} (h : Accepted rules A M C) (π : ℕ → ScanRule) + (hπ : ∀ i < rules.length, rules[i]? = some (π i)) + (hℓ : A.protectedCount ≤ rules.length) {i : ℕ} (hi : i < A.protectedCount) + {H : Set Cantor} (hH : fairCoin.real (H ∆ highSet A i) < (A.error : ℝ)) : + fairCoin.real {Z | Z ∈ H ∧ readFraction (π i) C.1.toFinset Z < 1} < + 4 * (A.error : ℝ) := + PoolSoundness.high_failure_lt (readFractionBy_le_readFraction _ _ _) hH + ((h.measure_spec π hπ hℓ).1 i hi) + +/-- The accepted finite tests control nearly full eventual coverage on the +strict low set, provided the fixed limiting function has the stated margin. -/ +theorem Accepted.low_near_full_lt {rules : List ScanRule} {A : Advice} {M : ℕ} + {C : Candidate} (h : Accepted rules A M C) (π : ℕ → ScanRule) + (hπ : ∀ i < rules.length, rules[i]? = some (π i)) + (hℓ : A.protectedCount ≤ rules.length) {B : ℝ} + (hB : ∑ i ∈ Finset.range rules.length, + (weight i : ℝ) * ∫ Z, readFraction (π i) C.1.toFinset Z ∂fairCoin ≤ B) + (hgap : B - (A.threshold : ℝ) < 4 * protectedWeight A * (A.error : ℝ)) + {i : ℕ} (hi : i < A.protectedCount) {g : Cantor → ℝ} + (hg : Integrable g fairCoin) + (happrox : (∫ Z, |approx A i Z - g Z| ∂fairCoin) < (A.error : ℝ)) + {τ ε : ℝ} (hτ : 0 < τ) + (hmargin : fairCoin.real {Z | 1 - 2 * τ < g Z ∧ g Z < 1} < ε) : + fairCoin.real {Z | g Z < 1 ∧ 1 - τ < readFraction (π i) C.1.toFinset Z} < + ε + 8 * (A.error : ℝ) / τ := + PoolSoundness.low_near_full_lt (integrable_readFraction _ _) hg hτ + (h.final_l1_lt π hπ hℓ hB hgap hi hg happrox) hmargin + +end Klr.PoolAdvice diff --git a/LeanPool/KLRandomness/PoolWeakLimit.lean b/LeanPool/KLRandomness/PoolWeakLimit.lean new file mode 100644 index 0000000000..5fedcce39e --- /dev/null +++ b/LeanPool/KLRandomness/PoolWeakLimit.lean @@ -0,0 +1,170 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import Mathlib.Analysis.InnerProductSpace.Dual +public import Mathlib.Analysis.Normed.Module.WeakDual +public import Mathlib.MeasureTheory.Function.AEEqOfIntegral +public import Mathlib.MeasureTheory.Function.L2Space +public import Mathlib.MeasureTheory.Measure.SeparableMeasure +public import Mathlib.Topology.Metrizable.Basic +public import Mathlib.Topology.Sequences +import Mathlib.Tactic.NormNum + +/-! +# Simultaneous weak limits for pool indicators + +A countable family of bounded sequences in a separable real Hilbert space has a +common weakly convergent subsequence. We prove this using the compact metrizable +weak-dual unit ball and Riesz representation. In particular, the weak limits +used for the fixed partitions in the pool lemma are obtained from Mathlib's +Banach--Alaoglu theorem, rather than supplied as an additional hypothesis. + +For probability-space `L²`, weak limits of functions with values almost +everywhere in `[0,1]` still have values almost everywhere in `[0,1]`. Testing +against the indicator of a measurable set also gives convergence of every set +integral. These are the interfaces needed by the fixed-partition construction. +-/ + +@[expose] public section + +noncomputable section + +namespace Klr.Pool + +open Filter MeasureTheory Set Topology +open scoped ENNReal + +section Hilbert + +variable {E : Type*} [NormedAddCommGroup E] [InnerProductSpace ℝ E] + +/-- Weak convergence of a sequence in a real inner product space. -/ +def WeaklyConverges (u : ℕ → E) (g : E) : Prop := + ∀ h : E, Tendsto (fun n => inner ℝ (u n) h) atTop (𝓝 (inner ℝ g h)) + +theorem WeaklyConverges.subseq {u : ℕ → E} {g : E} + (hu : WeaklyConverges u g) {φ : ℕ → ℕ} (hφ : StrictMono φ) : + WeaklyConverges (u ∘ φ) g := + fun h => (hu h).comp hφ.tendsto_atTop + +/-- All sequences in a countable family in the Hilbert unit ball admit one +common weakly convergent subsequence. The limits remain in the unit ball. -/ +theorem exists_simultaneous_weak_subsequence [CompleteSpace E] + [TopologicalSpace.SeparableSpace E] (u : ℕ → ℕ → E) + (hu : ∀ i n, ‖u i n‖ ≤ 1) : + ∃ (φ : ℕ → ℕ) (g : ℕ → E), StrictMono φ ∧ + (∀ i, ‖g i‖ ≤ 1) ∧ ∀ i, WeaklyConverges (u i ∘ φ) (g i) := by + let K : Set (WeakDual ℝ E) := + WeakDual.toStrongDual ⁻¹' Metric.closedBall (0 : StrongDual ℝ E) 1 + have hK : IsCompact K := WeakDual.isCompact_closedBall 0 1 + let : CompactSpace K := isCompact_iff_compactSpace.mp hK + let : TopologicalSpace.MetrizableSpace K := + WeakDual.metrizable_of_isCompact ℝ E K hK + let v : ℕ → ℕ → K := fun n i => + ⟨StrongDual.toWeakDual (InnerProductSpace.toDual ℝ E (u i n)), by + simpa [K, Metric.mem_closedBall, dist_zero_right] using hu i n⟩ + obtain ⟨vlim, φ, hφ, hvlim⟩ := CompactSpace.tendsto_subseq v + let g : ℕ → E := fun i => + (InnerProductSpace.toDual ℝ E).symm (WeakDual.toStrongDual (vlim i).val) + refine ⟨φ, g, hφ, ?_, ?_⟩ + · intro i + dsimp [g] + rw [(InnerProductSpace.toDual ℝ E).symm.norm_map] + have hb := (vlim i).property + change dist (WeakDual.toStrongDual (vlim i).val) 0 ≤ 1 at hb + simpa only [dist_zero_right] using hb + · intro i h + have hi' : Tendsto (fun n => v (φ n) i) atTop (𝓝 (vlim i)) := + (tendsto_pi_nhds.mp hvlim) i + have hi : Tendsto (fun n => (v (φ n) i).val) atTop (𝓝 (vlim i).val) := + continuous_subtype_val.continuousAt.tendsto.comp hi' + have he := (WeakDual.eval_continuous h).continuousAt.tendsto.comp hi + simpa [v, g, Function.comp_def] using he + +/-- A scalar convergence already arranged before the simultaneous extraction is +preserved. This is used after choosing positions whose weighted query +probabilities converge to their limsup. -/ +theorem exists_simultaneous_weak_subsequence_preserving [CompleteSpace E] + [TopologicalSpace.SeparableSpace E] (u : ℕ → ℕ → E) + (hu : ∀ i n, ‖u i n‖ ≤ 1) {p : ℕ → ℝ} {pstar : ℝ} + (hp : Tendsto p atTop (𝓝 pstar)) : + ∃ (φ : ℕ → ℕ) (g : ℕ → E), StrictMono φ ∧ + Tendsto (p ∘ φ) atTop (𝓝 pstar) ∧ + (∀ i, ‖g i‖ ≤ 1) ∧ ∀ i, WeaklyConverges (u i ∘ φ) (g i) := by + obtain ⟨φ, g, hφ, hg, hconv⟩ := exists_simultaneous_weak_subsequence u hu + exact ⟨φ, g, hφ, hp.comp hφ.tendsto_atTop, hg, hconv⟩ + +end Hilbert + +section L2 + +variable {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} [IsFiniteMeasure μ] + +/-- An `L²` function on a finite measure space is integrable. -/ +theorem integrable_L2 (f : Lp ℝ 2 μ) : Integrable f μ := by + exact memLp_one_iff_integrable.mp ((Lp.memLp f).mono_exponent (by norm_num)) + +/-- Weak `L²` convergence implies convergence of every measurable set integral. -/ +theorem WeaklyConverges.setIntegral {u : ℕ → Lp ℝ 2 μ} {g : Lp ℝ 2 μ} + (hu : WeaklyConverges u g) {s : Set Ω} (hs : MeasurableSet s) : + Tendsto (fun n => ∫ x in s, u n x ∂μ) atTop (𝓝 (∫ x in s, g x ∂μ)) := by + have h := hu (indicatorConstLp 2 hs (measure_ne_top μ s) (1 : ℝ)) + have htest (f : Lp ℝ 2 μ) : + inner ℝ f (indicatorConstLp 2 hs (measure_ne_top μ s) (1 : ℝ)) = + ∫ x in s, f x ∂μ := by + rw [real_inner_comm, L2.inner_indicatorConstLp_one] + simpa only [htest] using h + +/-- Positivity survives weak `L²` convergence. -/ +theorem WeaklyConverges.ae_nonneg {u : ℕ → Lp ℝ 2 μ} {g : Lp ℝ 2 μ} + (hu : WeaklyConverges u g) (hu0 : ∀ n, ∀ᵐ x ∂μ, 0 ≤ u n x) : + ∀ᵐ x ∂μ, 0 ≤ g x := by + refine ae_nonneg_of_forall_setIntegral_nonneg (integrable_L2 g) ?_ + intro s hs _ + exact ge_of_tendsto' (hu.setIntegral hs) fun n => + integral_nonneg_of_ae (ae_restrict_of_ae (hu0 n)) + +/-- An almost everywhere upper bound by one survives weak `L²` convergence. -/ +theorem WeaklyConverges.ae_le_one {u : ℕ → Lp ℝ 2 μ} {g : Lp ℝ 2 μ} + (hu : WeaklyConverges u g) (hu1 : ∀ n, ∀ᵐ x ∂μ, u n x ≤ 1) : + ∀ᵐ x ∂μ, g x ≤ 1 := by + refine ae_le_of_forall_setIntegral_le (integrable_L2 g) (integrable_const 1) ?_ + intro s hs _ + exact le_of_tendsto' (hu.setIntegral hs) fun n => + integral_mono_ae (integrable_L2 (u n)).integrableOn (integrable_const 1) + (ae_restrict_of_ae (hu1 n)) + +/-- A probability-space `L²` function with values in `[0,1]` is in the unit ball. -/ +theorem norm_le_one_of_ae_unitInterval [IsProbabilityMeasure μ] {f : Lp ℝ 2 μ} + (hf0 : ∀ᵐ x ∂μ, 0 ≤ f x) (hf1 : ∀ᵐ x ∂μ, f x ≤ 1) : ‖f‖ ≤ 1 := by + have hbound : ∀ᵐ x ∂μ, ‖f x‖ ≤ 1 := by + filter_upwards [hf0, hf1] with x hx0 hx1 + simpa [Real.norm_eq_abs, abs_of_nonneg hx0] using hx1 + simpa [measureUnivNNReal] using + Lp.norm_le_of_ae_bound (f := f) (by norm_num : (0 : ℝ) ≤ 1) hbound + +/-- The common weak subsequence required for the pool lemma, with the interval +bounds on the actual limits proved from weak convergence. -/ +theorem exists_unitInterval_weak_limits [IsProbabilityMeasure μ] + [MeasureTheory.IsSeparable μ] (u : ℕ → ℕ → Lp ℝ 2 μ) + (hu0 : ∀ i n, ∀ᵐ x ∂μ, 0 ≤ u i n x) + (hu1 : ∀ i n, ∀ᵐ x ∂μ, u i n x ≤ 1) : + ∃ (φ : ℕ → ℕ) (g : ℕ → Lp ℝ 2 μ), StrictMono φ ∧ + (∀ i, WeaklyConverges (u i ∘ φ) (g i)) ∧ + (∀ i, ∀ᵐ x ∂μ, 0 ≤ g i x) ∧ (∀ i, ∀ᵐ x ∂μ, g i x ≤ 1) := by + let : Fact ((2 : ℝ≥0∞) ≠ ∞) := ⟨by norm_num⟩ + obtain ⟨φ, g, hφ, _, hconv⟩ := exists_simultaneous_weak_subsequence u + (fun i n => norm_le_one_of_ae_unitInterval (hu0 i n) (hu1 i n)) + exact ⟨φ, g, hφ, hconv, fun i => (hconv i).ae_nonneg (fun n => hu0 i (φ n)), + fun i => (hconv i).ae_le_one (fun n => hu1 i (φ n))⟩ + +end L2 + +end Klr.Pool diff --git a/LeanPool/KLRandomness/PoolWeighted.lean b/LeanPool/KLRandomness/PoolWeighted.lean new file mode 100644 index 0000000000..36f23cffd1 --- /dev/null +++ b/LeanPool/KLRandomness/PoolWeighted.lean @@ -0,0 +1,268 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.PoolPartitionQuery +public import Mathlib.Analysis.Normed.Group.Tannery +public import Mathlib.Topology.Order.LiminfLimsup +import Mathlib.Tactic.Linarith +import Mathlib.Tactic.NormNum +import Mathlib.Tactic.Positivity + +/-! +# Weighted query probabilities and the limsup subsequence + +The paper numbers scans starting at one. Our zero-based index therefore has +`weight i = 2⁻(i+1)`, using exactly the paper's weights, whose sum is one. + +The weighted query probability is an actual convergent series with a uniform +geometric tail bound. We extract positions tending to infinity along which +this probability tends to its limsup, and prove the eventual upper bound used +in the finite pool construction. The common weak-limit extraction preserves +this scalar limit. Dominated convergence for series identifies the limsup +with the weighted integrals of the weak limits. +-/ + +@[expose] public section + +noncomputable section + +namespace Klr.Pool + +open Filter MeasureTheory Set Topology +open scoped ENNReal BigOperators + +/-- Normalized geometric weights on the countable family of scans. -/ +def weight (i : ℕ) : ℝ := (1 / 2 : ℝ) ^ (i + 1) + +theorem weight_pos (i : ℕ) : 0 < weight i := by + unfold weight + positivity + +theorem weight_nonneg (i : ℕ) : 0 ≤ weight i := (weight_pos i).le + +theorem summable_weight : Summable weight := by + change Summable (fun i => (1 / 2 : ℝ) ^ (i + 1)) + simpa only [pow_succ] using summable_geometric_two.mul_right (1 / 2) + +theorem tsum_weight : ∑' i, weight i = 1 := by + simp only [weight, pow_succ, tsum_mul_right, tsum_geometric_two] + norm_num + +theorem tsum_weight_tail (D : ℕ) : ∑' i, weight (i + D) = (1 / 2 : ℝ) ^ D := by + calc + ∑' i, weight (i + D) = ∑' i, weight i * (1 / 2 : ℝ) ^ D := by + apply tsum_congr + intro i + simp only [weight, ← pow_add] + congr 1 + omega + _ = (∑' i, weight i) * (1 / 2 : ℝ) ^ D := tsum_mul_right + _ = (1 / 2 : ℝ) ^ D := by rw [tsum_weight, one_mul] + +/-- The probability that the scan eventually queries the stated position. -/ +def queryProbability (π : ScanRule) (a : ℕ) : ℝ := + ∫ Z, PoolQuery.indicator π a Z ∂fairCoin + +theorem queryProbability_nonneg (π : ScanRule) (a : ℕ) : 0 ≤ queryProbability π a := + integral_nonneg fun Z => (PoolQuery.indicator_bounds π a Z).1 + +theorem queryProbability_le_one (π : ScanRule) (a : ℕ) : queryProbability π a ≤ 1 := by + calc + queryProbability π a ≤ ∫ _Z : Cantor, (1 : ℝ) ∂fairCoin := + integral_mono (PoolQuery.integrable_indicator π a) (integrable_const 1) + fun Z => (PoolQuery.indicator_bounds π a Z).2 + _ = 1 := by simp + +theorem queryProbability_eq_measureReal (π : ScanRule) (a : ℕ) : + queryProbability π a = fairCoin.real {Z | PoolQuery.Reads π a Z} := by + unfold queryProbability PoolQuery.indicator + rw [integral_indicator_const 1 (PoolQuery.measurableSet_reads π a)] + simp + +theorem integral_queryL2 (π : ScanRule) (a : ℕ) : + ∫ Z, queryL2 π a Z ∂fairCoin = queryProbability π a := + integral_congr_ae (queryL2_coeFn π a) + +/-- The normalized weighted eventual-query probability of a position. -/ +def weightedQueryProbability (π : ℕ → ScanRule) (a : ℕ) : ℝ := + ∑' i, weight i * queryProbability (π i) a + +theorem weighted_term_nonneg (π : ℕ → ScanRule) (a i : ℕ) : + 0 ≤ weight i * queryProbability (π i) a := + mul_nonneg (weight_nonneg i) (queryProbability_nonneg _ _) + +theorem weighted_term_le_weight (π : ℕ → ScanRule) (a i : ℕ) : + weight i * queryProbability (π i) a ≤ weight i := + mul_le_of_le_one_right (weight_nonneg i) (queryProbability_le_one _ _) + +theorem summable_weighted_query (π : ℕ → ScanRule) (a : ℕ) : + Summable (fun i => weight i * queryProbability (π i) a) := + Summable.of_nonneg_of_le (weighted_term_nonneg π a) (weighted_term_le_weight π a) + summable_weight + +theorem weightedQueryProbability_nonneg (π : ℕ → ScanRule) (a : ℕ) : + 0 ≤ weightedQueryProbability π a := + tsum_nonneg (weighted_term_nonneg π a) + +theorem weightedQueryProbability_le_one (π : ℕ → ScanRule) (a : ℕ) : + weightedQueryProbability π a ≤ 1 := by + calc + weightedQueryProbability π a ≤ ∑' i, weight i := + (summable_weighted_query π a).tsum_le_tsum (weighted_term_le_weight π a) summable_weight + _ = 1 := tsum_weight + +/-- The omitted scans contribute at most the geometric tail, uniformly in the +position. -/ +theorem weighted_query_tail_le (π : ℕ → ScanRule) (a D : ℕ) : + (∑' i, weight (i + D) * queryProbability (π (i + D)) a) ≤ (1 / 2 : ℝ) ^ D := by + have hleft := (summable_weighted_query π a).comp_injective + (fun i j (h : i + D = j + D) => Nat.add_right_cancel h) + have hright := summable_weight.comp_injective + (fun i j (h : i + D = j + D) => Nat.add_right_cancel h) + calc + (∑' i, weight (i + D) * queryProbability (π (i + D)) a) ≤ ∑' i, weight (i + D) := + hleft.tsum_le_tsum (fun i => weighted_term_le_weight π a (i + D)) hright + _ = (1 / 2 : ℝ) ^ D := tsum_weight_tail D + +theorem weighted_query_truncation (π : ℕ → ScanRule) (a D : ℕ) : + 0 ≤ weightedQueryProbability π a - + ∑ i ∈ Finset.range D, weight i * queryProbability (π i) a ∧ + weightedQueryProbability π a - + ∑ i ∈ Finset.range D, weight i * queryProbability (π i) a ≤ (1 / 2 : ℝ) ^ D := by + have hsplit := (summable_weighted_query π a).sum_add_tsum_nat_add D + have htail0 : 0 ≤ ∑' i, weight (i + D) * queryProbability (π (i + D)) a := + tsum_nonneg fun i => weighted_term_nonneg π a (i + D) + have htail1 := weighted_query_tail_le π a D + change _ = weightedQueryProbability π a at hsplit + constructor <;> linarith + +/-- The weighted-probability limsup at positions tending to infinity. -/ +def weightedQueryLimsup (π : ℕ → ScanRule) : ℝ := + limsup (weightedQueryProbability π) atTop + +theorem weighted_query_isBounded (π : ℕ → ScanRule) : + IsBoundedUnder (· ≤ ·) atTop (weightedQueryProbability π) := + isBoundedUnder_of ⟨1, weightedQueryProbability_le_one π⟩ + +theorem weighted_query_isCobounded (π : ℕ → ScanRule) : + IsCoboundedUnder (· ≤ ·) atTop (weightedQueryProbability π) := + isCoboundedUnder_le_of_le atTop (weightedQueryProbability_nonneg π) + +/-- Positions tend to infinity while their weighted query probabilities tend +to the actual limsup. -/ +theorem exists_weighted_limsup_sequence (π : ℕ → ScanRule) : + ∃ a : ℕ → ℕ, Tendsto a atTop atTop ∧ + Tendsto (weightedQueryProbability π ∘ a) atTop (𝓝 (weightedQueryLimsup π)) := by + obtain ⟨a, hp, ha⟩ := exists_seq_tendsto_limsup + (weighted_query_isCobounded π) (weighted_query_isBounded π) + exact ⟨a, ha, hp⟩ + +theorem weightedQueryLimsup_bounds (π : ℕ → ScanRule) : + 0 ≤ weightedQueryLimsup π ∧ weightedQueryLimsup π ≤ 1 := by + obtain ⟨a, _, hp⟩ := exists_weighted_limsup_sequence π + exact ⟨ge_of_tendsto' hp (fun n => weightedQueryProbability_nonneg π (a n)), + le_of_tendsto' hp (fun n => weightedQueryProbability_le_one π (a n))⟩ + +/-- After a sufficiently large position, every weighted query probability is +below the limsup plus any prescribed positive error. -/ +theorem eventually_weighted_query_lt (π : ℕ → ScanRule) {ε : ℝ} (hε : 0 < ε) : + ∀ᶠ a : ℕ in atTop, weightedQueryProbability π a < weightedQueryLimsup π + ε := + eventually_lt_of_limsup_lt (lt_add_of_pos_right _ hε) (weighted_query_isBounded π) + +theorem exists_weighted_query_upper_cutoff (π : ℕ → ScanRule) {ε : ℝ} (hε : 0 < ε) : + ∃ z : ℕ, ∀ a ≥ z, weightedQueryProbability π a < weightedQueryLimsup π + ε := + eventually_atTop.mp (eventually_weighted_query_lt π hε) + +namespace QueryPartition + +variable {π : ℕ → ScanRule} {a : ℕ → ℕ} (D : QueryPartition π a) + +theorem integral_representative (i : ℕ) : + ∫ Z, D.representative i Z ∂fairCoin = ∫ Z, D.limit i Z ∂fairCoin := + integral_congr_ae (D.representative_ae_eq i) + +theorem integral_limit_nonneg (i : ℕ) : 0 ≤ ∫ Z, D.limit i Z ∂fairCoin := + integral_nonneg_of_ae (D.limit_nonneg i) + +theorem integral_limit_le_one (i : ℕ) : (∫ Z, D.limit i Z ∂fairCoin) ≤ 1 := by + calc + (∫ Z, D.limit i Z ∂fairCoin) ≤ ∫ _Z : Cantor, (1 : ℝ) ∂fairCoin := + integral_mono_ae (integrable_L2 (D.limit i)) (integrable_const 1) (D.limit_le_one i) + _ = 1 := by simp + +theorem queryProbability_tendsto (i : ℕ) : + Tendsto (fun n => queryProbability (π i) (D.position n)) atTop + (𝓝 (∫ Z, D.limit i Z ∂fairCoin)) := by + simpa only [Measure.restrict_univ, integral_queryL2, position] using + (D.weak i).setIntegral MeasurableSet.univ + +theorem finite_weighted_tendsto (k : ℕ) : + Tendsto (fun n => ∑ i ∈ Finset.range k, weight i * queryProbability (π i) (D.position n)) + atTop (𝓝 (∑ i ∈ Finset.range k, weight i * ∫ Z, D.limit i Z ∂fairCoin)) := + tendsto_finsetSum (Finset.range k) + (fun i _ => (D.queryProbability_tendsto i).const_mul (weight i)) + +/-- Weighted means commute with the common weak limit, because the normalized +geometric weights dominate all query probabilities. -/ +theorem weighted_tendsto : + Tendsto (weightedQueryProbability π ∘ D.position) atTop + (𝓝 (∑' i, weight i * ∫ Z, D.limit i Z ∂fairCoin)) := by + have h := tendsto_tsum_of_dominated_convergence summable_weight + (fun i => (D.queryProbability_tendsto i).const_mul (weight i)) + (Filter.Eventually.of_forall fun n i => by + rw [Real.norm_eq_abs, abs_of_nonneg (weighted_term_nonneg π (D.position n) i)] + exact weighted_term_le_weight π (D.position n) i) + exact h + +theorem weighted_limit_eq_limsup + (hp : Tendsto (weightedQueryProbability π ∘ a) atTop (𝓝 (weightedQueryLimsup π))) : + (∑' i, weight i * ∫ Z, D.limit i Z ∂fairCoin) = weightedQueryLimsup π := + tendsto_nhds_unique D.weighted_tendsto (D.scalar_tendsto hp) + +/-- Finite truncation of the limiting weighted integrals has the same uniform +geometric error bound as the original query probabilities. -/ +theorem weighted_limit_truncation {pstar : ℝ} + (hp : Tendsto (weightedQueryProbability π ∘ D.position) atTop (𝓝 pstar)) (k : ℕ) : + 0 ≤ pstar - ∑ i ∈ Finset.range k, weight i * ∫ Z, D.limit i Z ∂fairCoin ∧ + pstar - ∑ i ∈ Finset.range k, weight i * ∫ Z, D.limit i Z ∂fairCoin ≤ + (1 / 2 : ℝ) ^ k := by + have hdiff := hp.sub (D.finite_weighted_tendsto k) + exact ⟨ge_of_tendsto' hdiff (fun n => (weighted_query_truncation π (D.position n) k).1), + le_of_tendsto' hdiff (fun n => (weighted_query_truncation π (D.position n) k).2)⟩ + +/-- A rational or real threshold below the limiting finite-prefix mass has a +fixed positive slack, eventually along the query subsequence. -/ +theorem eventually_finite_weighted_above {pstar γ : ℝ} + (hp : Tendsto (weightedQueryProbability π ∘ D.position) atTop (𝓝 pstar)) (k : ℕ) + (hγ : γ + (1 / 2 : ℝ) ^ k < pstar) : + ∃ ε : ℝ, 0 < ε ∧ ∀ᶠ n : ℕ in atTop, + γ + ε < ∑ i ∈ Finset.range k, weight i * queryProbability (π i) (D.position n) := by + let S : ℝ := ∑ i ∈ Finset.range k, weight i * ∫ Z, D.limit i Z ∂fairCoin + have hS : γ < S := by + have ht := (D.weighted_limit_truncation hp k).2 + dsimp [S] + linarith + refine ⟨(S - γ) / 2, by linarith, ?_⟩ + have hmid : γ + (S - γ) / 2 < S := by linarith + exact (D.finite_weighted_tendsto k).eventually (lt_mem_nhds hmid) + +end QueryPartition + +/-- The fixed Borel partition data can be chosen along positions tending to +infinity and preserving the weighted limsup. -/ +theorem exists_weighted_queryPartition (π : ℕ → ScanRule) : + ∃ (a : ℕ → ℕ) (D : QueryPartition π a), Tendsto D.position atTop atTop ∧ + Tendsto (weightedQueryProbability π ∘ D.position) atTop (𝓝 (weightedQueryLimsup π)) ∧ + (∑' i, weight i * ∫ Z, D.limit i Z ∂fairCoin) = weightedQueryLimsup π := by + obtain ⟨a, ha, hp⟩ := exists_weighted_limsup_sequence π + obtain ⟨D⟩ := exists_queryPartition π a + exact ⟨a, D, D.positions_tendsto ha, D.scalar_tendsto hp, D.weighted_limit_eq_limsup hp⟩ + +end Klr.Pool diff --git a/LeanPool/KLRandomness/PoolWitness.lean b/LeanPool/KLRandomness/PoolWitness.lean new file mode 100644 index 0000000000..a11ffc9545 --- /dev/null +++ b/LeanPool/KLRandomness/PoolWitness.lean @@ -0,0 +1,133 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.PoolSelection +public import LeanPool.KLRandomness.PoolQueryLimit +public import LeanPool.KLRandomness.PoolWeighted +public import LeanPool.KLRandomness.PoolSoundness + +/-! +# Actual finite witnesses for the pool search + +The weak-limit selection is applied to the actual query indicators. It gives +arbitrarily large finite pools with small missed mass on the fixed high sets, +small L1 distance to the fixed limits, and the required weighted coverage. +Finite-horizon convergence then supplies an actual pair accepted by the +executable checker. No convergence modulus is supplied to that checker. +-/ + +@[expose] public section + +namespace Klr.Pool + +open Filter MeasureTheory +open scoped Topology BigOperators symmDiff + +theorem advice_weight_cast (i : ℕ) : (PoolAdvice.weight i : ℝ) = weight i := by + simp [PoolAdvice.weight, weight] + +/-- Weighted eventual coverage using a finite prefix of the scans. -/ +noncomputable def finitePoolMass (π : ℕ → ScanRule) (k : ℕ) (G : Finset ℕ) : ℝ := + ∑ i ∈ Finset.range k, weight i * ∫ Z, PoolQuery.readFraction (π i) G Z ∂fairCoin + +theorem integral_readFraction (π : ScanRule) (G : Finset ℕ) : + (∫ Z, PoolQuery.readFraction π G Z ∂fairCoin) = + (∑ a ∈ G, queryProbability π a) / G.card := by + unfold PoolQuery.readFraction queryProbability + rw [integral_div, integral_finsetSum _ (fun a _ => PoolQuery.integrable_indicator π a)] + +/-- Average weighted coverage is the average of the positions' weighted +query probabilities. -/ +theorem finitePoolMass_eq_average (π : ℕ → ScanRule) (k : ℕ) (G : Finset ℕ) : + finitePoolMass π k G = + (∑ a ∈ G, ∑ i ∈ Finset.range k, weight i * queryProbability (π i) a) / G.card := by + unfold finitePoolMass + simp_rw [integral_readFraction, ← mul_div_assoc, Finset.mul_sum] + rw [← Finset.sum_div, Finset.sum_comm] + +/-- Reindexing a distinct selection of indices gives the actual centered pool +average, with no multiplicities hidden in the finite set. -/ +theorem averageL2_image_sub (π : ScanRule) (a : ℕ → ℕ) (F : Finset ℕ) + (hinj : Set.InjOn a F) (hF : F.Nonempty) (g : Lp ℝ 2 fairCoin) : + averageL2 π (F.image a) - g = + (F.card : ℝ)⁻¹ • ∑ n ∈ F, (queryL2 π (a n) - g) := by + classical + have hc : (F.card : ℝ) ≠ 0 := by exact_mod_cast hF.card_ne_zero + rw [averageL2, Finset.card_image_of_injOn hinj, + Finset.sum_image (fun n hn m hm h => hinj hn hm h), Finset.sum_sub_distrib, + Finset.sum_const, ← Nat.cast_smul_eq_nsmul ℝ, smul_sub, smul_smul, + inv_mul_cancel₀ hc, one_smul] + +namespace QueryPartition + +variable {π : ℕ → ScanRule} {a : ℕ → ℕ} (D : QueryPartition π a) + +/-- Actual finite pools satisfying the limiting tests exist at every +sufficiently large size. The weighted lower bound is an eventual property of +the chosen query positions; `PoolWeighted` obtains it from the limsup. -/ +theorem eventually_exists_final_pool (ha : Tendsto D.position atTop atTop) + (ℓ k z : ℕ) {δ γ : ℝ} (hδ : 0 < δ) + (hweighted : ∀ᶠ n : ℕ in atTop, + γ < ∑ i ∈ Finset.range k, weight i * queryProbability (π i) (D.position n)) : + ∀ᶠ M : ℕ in atTop, ∃ G : Finset ℕ, + G.card = M ∧ (∀ b ∈ G, z ≤ b) ∧ + (∀ i < ℓ, fairCoin.real {Z | Z ∈ D.high i ∧ PoolQuery.readFraction (π i) G Z < 1} < δ) ∧ + (∀ i < ℓ, (∫ Z, |PoolQuery.readFraction (π i) G Z - D.representative i Z| ∂fairCoin) < δ) ∧ + γ < finitePoolMass π k G := by + classical + have hselect := eventually_exists_finite_weak_average + (fun i n => queryL2 (π i) (D.position n)) D.limit D.weak + (fun i n => norm_queryL2_le_one (π i) (D.position n)) + (fun i => norm_le_one_of_ae_unitInterval (D.limit_nonneg i) (D.limit_le_one i)) + D.position ha ℓ hδ + filter_upwards [eventually_ge_atTop 1, hselect] with M hM hselect + have hMr : (0 : ℝ) < M := by exact_mod_cast (show 0 < M by omega) + let P : ℕ → Prop := fun n => z ≤ D.position n ∧ + (∀ i < ℓ, fairCoin.real (D.high i \ {Z | PoolQuery.Reads (π i) (D.position n) Z}) < + δ / M) ∧ γ < ∑ i ∈ Finset.range k, weight i * queryProbability (π i) (D.position n) + have hP : ∀ᶠ n : ℕ in atTop, P n := by + have hhigh : ∀ᶠ n : ℕ in atTop, ∀ i : Fin ℓ, + fairCoin.real (D.high i \ {Z | PoolQuery.Reads (π i) (D.position n) Z}) < δ / M := + Filter.eventually_all.mpr fun i => (D.high_miss_tendsto_zero i).eventually + (gt_mem_nhds (div_pos hδ hMr)) + filter_upwards [ha.eventually (eventually_ge_atTop z), hhigh, hweighted] with n hz hh hw + exact ⟨hz, fun i hi => hh ⟨i, hi⟩, hw⟩ + obtain ⟨F, hcard, hPF, hinj, hnorm⟩ := hselect P hP + let G := F.image D.position + have hGcard : G.card = M := (Finset.card_image_of_injOn hinj).trans hcard + have hG : G.Nonempty := Finset.card_pos.mp (by omega) + have hF : F.Nonempty := Finset.card_pos.mp (by omega) + have hside : ∀ b ∈ G, z ≤ b ∧ + (∀ i < ℓ, fairCoin.real (D.high i \ {Z | PoolQuery.Reads (π i) b Z}) < δ / M) ∧ + γ < ∑ i ∈ Finset.range k, weight i * queryProbability (π i) b := by + intro b hb + obtain ⟨n, hn, rfl⟩ := Finset.mem_image.mp hb + exact hPF n hn + refine ⟨G, hGcard, fun b hb => (hside b hb).1, ?_, ?_, ?_⟩ + · intro i hi + calc + _ ≤ ∑ b ∈ G, fairCoin.real (D.high i \ {Z | PoolQuery.Reads (π i) b Z}) := + PoolQuery.high_miss_le_sum (π i) hG (D.high i) + _ < ∑ _b ∈ G, δ / (M : ℝ) := + Finset.sum_lt_sum_of_nonempty hG (fun b hb => (hside b hb).2.1 i hi) + _ = δ := by simp [hGcard, nsmul_eq_mul, mul_div_cancel₀ δ hMr.ne'] + · intro i hi + apply (D.integral_abs_readFraction_sub_representative_le i G).trans_lt + rw [show G = F.image D.position from rfl, averageL2_image_sub _ _ _ hinj hF] + exact hnorm i hi + · rw [finitePoolMass_eq_average] + apply (lt_div_iff₀ (by exact_mod_cast hG.card_pos)).mpr + calc + γ * (G.card : ℝ) = ∑ _b ∈ G, γ := by simp [mul_comm] + _ < _ := Finset.sum_lt_sum_of_nonempty hG (fun b hb => (hside b hb).2.2) + +end QueryPartition + +end Klr.Pool diff --git a/LeanPool/KLRandomness/PrefixStage.lean b/LeanPool/KLRandomness/PrefixStage.lean new file mode 100644 index 0000000000..94956e4ce4 --- /dev/null +++ b/LeanPool/KLRandomness/PrefixStage.lean @@ -0,0 +1,236 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.AffineAnswer +import Mathlib.Tactic.NormNum + +/-! +# Prefixes of the finite-stage block laws + +For a sequence of pairwise disjoint affine blocks, stage `n` conditions fair +coin on blocks `0, ..., n - 1`. The laws are probability measures. Adding a +block preserves a transcript while its unread columns have full rank, and +preserves every event on coordinates disjoint from the added block. + +Both identities telescope across arbitrary finite intervals of stages. The +supported-event identity supplies the consistency needed to construct the +eventual block law from its finite-coordinate marginals. +-/ + +@[expose] public section + +namespace Klr.PrefixStage + +open MeasureTheory ProbabilityTheory AffineBlock FiniteStage StoppingTranscript +open scoped ENNReal + +/-- The first `n` blocks, indexed by `Fin n`. -/ +def prefixFamily (B : ℕ → AffineBlock) (n : ℕ) : Fin n → AffineBlock := fun i => B i.val + +/-- All equations imposed before stage `n`. -/ +def prefixEvent (B : ℕ → AffineBlock) (n : ℕ) : Set Cantor := + familyEvent (prefixFamily B n) + +/-- All coordinates used by the first `n` blocks. -/ +def prefixSupport (B : ℕ → AffineBlock) (n : ℕ) : Finset ℕ := + familySupport (prefixFamily B n) + +/-- The actual stage-`n` probability law, before block `n` is imposed. -/ +noncomputable def law (B : ℕ → AffineBlock) (n : ℕ) : Measure Cantor := + finiteStageLaw (prefixFamily B n) + +theorem law_eq_cond (B : ℕ → AffineBlock) (n : ℕ) : + law B n = cond fairCoin (prefixEvent B n) := rfl + +@[simp] theorem mem_prefixEvent (B : ℕ → AffineBlock) (n : ℕ) (X : Cantor) : + X ∈ prefixEvent B n ↔ ∀ k < n, X ∈ (B k).event := by + change (∀ i : Fin n, X ∈ (B i.val).event) ↔ _ + exact ⟨fun h k hk => h ⟨k, hk⟩, fun h i => h i.val i.isLt⟩ + +@[simp] theorem prefixEvent_zero (B : ℕ → AffineBlock) : prefixEvent B 0 = Set.univ := by + ext X + simp + +theorem prefixEvent_succ (B : ℕ → AffineBlock) (n : ℕ) : + prefixEvent B (n + 1) = prefixEvent B n ∩ (B n).event := by + ext X + simp only [mem_prefixEvent, Set.mem_inter_iff] + constructor + · intro h + exact ⟨fun k hk => h k (by omega), h n (by omega)⟩ + · rintro ⟨h, hn⟩ k hk + rcases lt_or_eq_of_le (Nat.le_of_lt_succ hk) with hkn | rfl + · exact h k hkn + · exact hn + +theorem prefixEvent_antitone (B : ℕ → AffineBlock) : Antitone (prefixEvent B) := by + intro n m hnm X hX + exact (mem_prefixEvent B n X).mpr (fun k hk => + (mem_prefixEvent B m X).mp hX k (lt_of_lt_of_le hk hnm)) + +theorem measurableSet_prefixEvent (B : ℕ → AffineBlock) (n : ℕ) : + MeasurableSet (prefixEvent B n) := measurableSet_familyEvent (prefixFamily B n) + +theorem prefixEvent_dependsOn (B : ℕ → AffineBlock) (n : ℕ) : + DependsOn (fun X : Cantor => X ∈ prefixEvent B n) (prefixSupport B n : Set ℕ) := + familyEvent_dependsOn (prefixFamily B n) + +@[simp] theorem mem_prefixSupport (B : ℕ → AffineBlock) (n q : ℕ) : + q ∈ prefixSupport B n ↔ ∃ k, k < n ∧ q ∈ (B k).support := by + simp only [prefixSupport, familySupport, Finset.mem_biUnion, Finset.mem_univ, true_and] + exact ⟨fun ⟨i, hi⟩ => ⟨i.val, i.isLt, hi⟩, fun ⟨k, hk, hq⟩ => ⟨⟨k, hk⟩, hq⟩⟩ + +theorem prefixSupport_mono (B : ℕ → AffineBlock) : Monotone (prefixSupport B) := by + intro n m hnm q hq + obtain ⟨k, hk, hqk⟩ := (mem_prefixSupport B n q).mp hq + exact (mem_prefixSupport B m q).mpr ⟨k, lt_of_lt_of_le hk hnm, hqk⟩ + +theorem prefixFamily_pairwise (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) (n : ℕ) : + Pairwise (fun i j : Fin n => + Disjoint (prefixFamily B n i).support (prefixFamily B n j).support) := by + intro i j hij + exact hdis (fun h => hij (Fin.ext h)) + +theorem prefixSupport_disjoint_of_le (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) + {n k : ℕ} (hnk : n ≤ k) : Disjoint (prefixSupport B n) (B k).support := by + apply Finset.disjoint_left.mpr + intro q hq hqk + obtain ⟨j, hj, hqj⟩ := (mem_prefixSupport B n q).mp hq + exact Finset.disjoint_left.mp (hdis (by omega : j ≠ k)) hqj hqk + +theorem fairCoin_prefixEvent_ne_zero (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) (n : ℕ) : + fairCoin (prefixEvent B n) ≠ 0 := + fairCoin_familyEvent_ne_zero (prefixFamily B n) (prefixFamily_pairwise B hdis n) + +theorem law_isProbabilityMeasure (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) (n : ℕ) : + IsProbabilityMeasure (law B n) := + finiteStageLaw_isProbabilityMeasure_of_disjoint (prefixFamily B n) + (prefixFamily_pairwise B hdis n) + +@[simp] theorem law_zero (B : ℕ → AffineBlock) : law B 0 = fairCoin := by + rw [law_eq_cond, prefixEvent_zero] + simp + +/-- Successor stages add exactly the next affine constraint. -/ +theorem law_succ (B : ℕ → AffineBlock) (n : ℕ) : + law B (n + 1) = cond fairCoin (prefixEvent B n ∩ (B n).event) := by + rw [law_eq_cond, prefixEvent_succ] + +/-- The next stage is obtained by conditioning the present stage on its next block. -/ +theorem law_succ_eq_cond (B : ℕ → AffineBlock) (n : ℕ) : + law B (n + 1) = cond (law B n) (B n).event := by + rw [law_succ, law_eq_cond, + cond_cond_eq_cond_inter (measurableSet_prefixEvent B n) (B n).measurableSet_event fairCoin] + +/-- A block not yet imposed has its uniform syndrome mass under the current stage. -/ +theorem law_next_block_event (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) (n : ℕ) : + law B n (B n).event = (1 / 2 : ℝ≥0∞) ^ (B n).rank := by + apply finiteStageLaw_event_of_disjoint (prefixFamily B n) (B n) + (prefixFamily_pairwise B hdis n) + intro i + exact hdis (ne_of_lt i.isLt) + +/-- Every block already imposed holds with probability one at the current stage. -/ +theorem law_block_event (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) + (n k : ℕ) (hk : k < n) : law B n (B k).event = 1 := by + have hsub : prefixEvent B n ⊆ (B k).event := fun X hX => (mem_prefixEvent B n X).mp hX k hk + rw [law_eq_cond, cond_apply (measurableSet_prefixEvent B n), Set.inter_eq_left.mpr hsub, + ENNReal.inv_mul_cancel (fairCoin_prefixEvent_ne_zero B hdis n) (measure_ne_top _ _)] + +/-- One stage preserves a transcript whenever the new block's unread columns retain full rank. -/ +theorem law_succ_transcript (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) + (n : ℕ) (π : ScanRule) (v : List Bool) (hfull : (B n).UnreadFullRank π v) : + law B (n + 1) (inputEvent π v) = law B n (inputEvent π v) := by + rw [law_succ] + exact nextStageLaw_transcript (prefixFamily B n) (B n) + (prefixFamily_pairwise B hdis n) (fun i => hdis (ne_of_lt i.isLt)) π v hfull + +/-- Transcript equality telescopes through any finite interval of blocks that still +have full unread rank at the specified transcript. -/ +theorem law_transcript_eq_of_fullRank (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) + (n m : ℕ) (hnm : n ≤ m) (π : ScanRule) (v : List Bool) + (hfull : ∀ k, n ≤ k → k < m → (B k).UnreadFullRank π v) : + law B m (inputEvent π v) = law B n (inputEvent π v) := by + induction m with + | zero => + have hn : n = 0 := by omega + subst n + rfl + | succ m ih => + by_cases hnm' : n ≤ m + · rw [law_succ_transcript B hdis m π v (hfull m hnm' (by omega))] + exact ih hnm' (fun k hnk hkm => hfull k hnk (by omega)) + · have hn : n = m + 1 := by omega + subst n + rfl + +/-- A finite-coordinate event independent of the next block has the exact syndrome +factor under the current stage, including when that event has probability zero. -/ +theorem law_inter_next_of_disjoint (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) + (n : ℕ) (G : Finset ℕ) (A : Set Cantor) + (hA : DependsOn (fun X : Cantor => X ∈ A) (G : Set ℕ)) + (hnew : Disjoint G (B n).support) : + law B n (A ∩ (B n).event) = (1 / 2 : ℝ≥0∞) ^ (B n).rank * law B n A := by + have hdep : DependsOn (fun X : Cantor => X ∈ prefixEvent B n ∩ A) + ((prefixSupport B n ∪ G : Finset ℕ) : Set ℕ) := by + intro X Y hxy + have hP := prefixEvent_dependsOn B n (fun q hq => hxy q (Finset.mem_union_left _ hq)) + have hA' := hA (fun q hq => hxy q (Finset.mem_union_right _ hq)) + change ((X ∈ prefixEvent B n) ∧ X ∈ A) = ((Y ∈ prefixEvent B n) ∧ Y ∈ A) + exact congrArg₂ And hP hA' + have hd : Disjoint (prefixSupport B n ∪ G) (B n).support := + Finset.disjoint_union_left.mpr ⟨prefixSupport_disjoint_of_le B hdis le_rfl, hnew⟩ + have hind := fairCoin_inter_of_disjoint_support (prefixEvent B n ∩ A) (B n).event + (prefixSupport B n ∪ G) (B n).support hdep (B n).dependsOn_event hd + rw [law_eq_cond, cond_apply (measurableSet_prefixEvent B n), + cond_apply (measurableSet_prefixEvent B n), ← Set.inter_assoc, hind, (B n).fairCoin_event] + ac_rfl + +/-- Adding a block leaves every event on disjoint finite coordinates unchanged. -/ +theorem law_succ_apply_eq_of_disjoint (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) + (n : ℕ) (G : Finset ℕ) (A : Set Cantor) + (hA : DependsOn (fun X : Cantor => X ∈ A) (G : Set ℕ)) + (hnew : Disjoint G (B n).support) : law B (n + 1) A = law B n A := by + rw [law_succ_eq_cond, cond_apply (B n).measurableSet_event, Set.inter_comm, + law_inter_next_of_disjoint B hdis n G A hA hnew, law_next_block_event B hdis n, + ← mul_assoc, ENNReal.inv_mul_cancel (pow_ne_zero _ (by norm_num)) (by finiteness), one_mul] + +/-- Finite-coordinate probabilities stabilize across every finite interval of new +blocks disjoint from those coordinates. This is the marginal consistency identity. -/ +theorem law_apply_eq_of_disjoint (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) + {n m : ℕ} (hnm : n ≤ m) (G : Finset ℕ) (A : Set Cantor) + (hA : DependsOn (fun X : Cantor => X ∈ A) (G : Set ℕ)) + (hnew : ∀ k, n ≤ k → k < m → Disjoint G (B k).support) : + law B m A = law B n A := by + induction m with + | zero => + have hn : n = 0 := by omega + subst n + rfl + | succ m ih => + by_cases hnm' : n ≤ m + · rw [law_succ_apply_eq_of_disjoint B hdis m G A hA (hnew m hnm' (by omega))] + exact ih hnm' (fun k hnk hkm => hnew k hnk (by omega)) + · have hn : n = m + 1 := by omega + subst n + rfl + +end Klr.PrefixStage diff --git a/LeanPool/KLRandomness/RandomMatrix.lean b/LeanPool/KLRandomness/RandomMatrix.lean new file mode 100644 index 0000000000..a03cc26919 --- /dev/null +++ b/LeanPool/KLRandomness/RandomMatrix.lean @@ -0,0 +1,265 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.RandomMatrixAlgebra +public import LeanPool.KLRandomness.FiniteProbability +import Mathlib.Tactic.GCongr +import Mathlib.Tactic.Linarith +import Mathlib.Tactic.NormNum +import Mathlib.Tactic.Positivity + +/-! +# Uniform binary matrices and rank failure + +The probability space in this file consists of all binary matrices, with +the actual uniform counting probability. For every nonzero row functional, +its evaluations on any `N` selected columns are uniformly distributed in +`(ZMod 2)^N`. Union over the `2^r - 1` nonzero row functionals yields the +rank-failure estimate for an `r`-row matrix. +-/ + +@[expose] public section + +namespace Klr.RandomMatrix + +open scoped BigOperators +open FiniteProbability + +section Fiber + +variable {V W : Type*} [AddCommGroup V] [AddCommGroup W] + [Module (ZMod 2) V] [Module (ZMod 2) W] + [Fintype V] [Module.Finite (ZMod 2) V] + +/-- Every fiber of a surjective binary linear map has the same exact +uniform counting probability. -/ +theorem binary_fiber_probability (D : V →ₗ[ZMod 2] W) + (hD : Function.Surjective D) (z : W) : + probability {x | D x = z} = (1 / 2 : ℝ) ^ Module.finrank (ZMod 2) W := by + have hd := D.finrank_range_add_finrank_ker + rw [LinearMap.range_eq_top.mpr hD, finrank_top] at hd + have hr : Module.finrank (ZMod 2) W ≤ Module.finrank (ZMod 2) V := by omega + rw [probability_eq_card] + change (Nat.card (Affine.Fiber D z) : ℝ) / Fintype.card V = _ + rw [Affine.card_fiber_of_surjective D hD z, Module.card_eq_pow_finrank (K := ZMod 2)] + simp only [Nat.card_zmod, ZMod.card, Nat.cast_pow, Nat.cast_ofNat] + have hp : (2 : ℝ) ^ Module.finrank (ZMod 2) V = + 2 ^ (Module.finrank (ZMod 2) V - Module.finrank (ZMod 2) W) * + 2 ^ Module.finrank (ZMod 2) W := by + rw [← pow_add, Nat.sub_add_cancel hr] + rw [hp, div_mul_eq_div_div, div_self (by positivity)] + simp + +end Fiber + +variable {ι : Type*} [Fintype ι] [DecidableEq ι] {r : ℕ} + +/-- The sample space of all binary `r`-row matrices with columns indexed by `ι`. -/ +abbrev BinaryMatrix (ι : Type*) (r : ℕ) := ι → (Fin r → ZMod 2) + +instance finiteBinaryDual : Finite (Module.Dual (ZMod 2) (Fin r → ZMod 2)) := + Finite.of_injective + (fun φ : Module.Dual (ZMod 2) (Fin r → ZMod 2) => (φ : (Fin r → ZMod 2) → ZMod 2)) + DFunLike.coe_injective + +/-- A fixed nonzero row combination vanishes on all selected columns with +probability exactly `2^(-T.card)`. -/ +theorem annihilator_probability (φ : Module.Dual (ZMod 2) (Fin r → ZMod 2)) + (hφ : φ ≠ 0) (T : Finset ι) : + probability {B : BinaryMatrix ι r | evaluationMap φ T B = 0} = + (1 / 2 : ℝ) ^ T.card := by + simpa using binary_fiber_probability (evaluationMap φ T) + (evaluationMap_surjective hφ T) 0 + +/-- There are exactly `2^r - 1` nonzero row functionals. -/ +theorem card_nonzero_dual : + Nat.card {φ : Module.Dual (ZMod 2) (Fin r → ZMod 2) // φ ≠ 0} = 2 ^ r - 1 := by + classical + let _ := Fintype.ofFinite (Module.Dual (ZMod 2) (Fin r → ZMod 2)) + rw [Nat.card_eq_fintype_card, Fintype.card_subtype_compl, + Module.card_eq_pow_finrank (K := ZMod 2)] + simp [Subspace.dual_finrank_eq] + +/-- The union bound for actual uniformly chosen binary matrices. It applies +to an arbitrary finite column type, including a sampled support subtype. -/ +theorem restricted_failure_probability_le (T : Finset ι) : + probability {B : BinaryMatrix ι r | + ¬ Function.Surjective (restrictedMap B T (K := ZMod 2))} ≤ + ((2 ^ r - 1 : ℕ) : ℝ) * (1 / 2 : ℝ) ^ T.card := by + classical + let Φ := {φ : Module.Dual (ZMod 2) (Fin r → ZMod 2) // φ ≠ 0} + let _ : Fintype Φ := Fintype.ofFinite Φ + have he : {B : BinaryMatrix ι r | + ¬ Function.Surjective (restrictedMap B T (K := ZMod 2))} = + ⋃ φ : Φ, {B | evaluationMap φ.val T B = 0} := by + ext B + simp only [Set.mem_ofPred_eq, Set.mem_iUnion, restricted_not_surjective_iff] + exact ⟨fun ⟨φ, hφ, hB⟩ => ⟨⟨φ, hφ⟩, hB⟩, + fun ⟨φ, hB⟩ => ⟨φ.val, φ.property, hB⟩⟩ + rw [he] + calc + _ ≤ ∑ φ : Φ, probability {B : BinaryMatrix ι r | evaluationMap φ.val T B = 0} := + probability_iUnion_le _ + _ = (Fintype.card Φ : ℝ) * (1 / 2 : ℝ) ^ T.card := by + calc + _ = ∑ _φ : Φ, (1 / 2 : ℝ) ^ T.card := + Finset.sum_congr rfl (fun φ _ => annihilator_probability φ.val φ.property T) + _ = _ := by simp + _ = _ := by rw [← Nat.card_eq_fintype_card, card_nonzero_dual] + +/-- A binary matrix has full row rank when its column map is surjective. -/ +def FullRowRank (B : BinaryMatrix ι r) : Prop := + Function.Surjective (columnMap B (K := ZMod 2)) + +/-- The actual finite sample space used when the matrix is drawn uniformly +conditional on full row rank. -/ +abbrev FullRankMatrix (ι : Type*) [Fintype ι] (r : ℕ) := + ↥{B : BinaryMatrix ι r | FullRowRank B} + +noncomputable instance fullRankMatrixFintype : Fintype (FullRankMatrix ι r) := + Fintype.ofFinite _ + +/-- The full matrix itself fails full row rank with probability at most +`(2^r - 1) / 2^m`, where `m` is its number of columns. -/ +theorem failure_probability_le : + probability {B : BinaryMatrix ι r | ¬ FullRowRank B} ≤ + ((2 ^ r - 1 : ℕ) : ℝ) * (1 / 2 : ℝ) ^ Fintype.card ι := by + simpa only [FullRowRank, restricted_univ_surjective_iff, Finset.card_univ] using + (restricted_failure_probability_le (r := r) (Finset.univ : Finset ι)) + +/-- The full-rank mass lower bound follows from the same union estimate. -/ +theorem full_rank_probability_ge : + 1 - ((2 ^ r - 1 : ℕ) : ℝ) * (1 / 2 : ℝ) ^ Fintype.card ι ≤ + probability {B : BinaryMatrix ι r | FullRowRank B} := by + have h := failure_probability_le (ι := ι) (r := r) + have hc := probability_compl {B : BinaryMatrix ι r | FullRowRank B} + change probability {B : BinaryMatrix ι r | ¬ FullRowRank B} = + 1 - probability {B : BinaryMatrix ι r | FullRowRank B} at hc + linarith + +section Conditioning + +variable {Ω : Type*} [Fintype Ω] [Nonempty Ω] + +/-- Uniformly sampling an event subtype is exactly conditioning uniform +counting probability on that event. This identity also holds for an empty +subtype, with the usual field convention for division by zero. -/ +theorem probability_subtype (A H : Set Ω) [Fintype H] : + probability {x : H | x.val ∈ A} = probability (A ∩ H) / probability H := by + classical + let e : ↥{x : H | x.val ∈ A} ≃ ↥(A ∩ H) := + { toFun := fun x => ⟨x.val.val, x.property, x.val.property⟩ + invFun := fun x => ⟨⟨x.val, x.property.2⟩, x.property.1⟩ + left_inv := fun x => rfl + right_inv := fun x => rfl } + rw [probability_eq_card, probability_eq_card, probability_eq_card, + Nat.card_congr e, Nat.card_eq_fintype_card (α := H)] + symm + exact div_div_div_cancel_right₀ (ne_of_gt (card_pos (Ω := Ω))) _ _ + +/-- Conditioning on an event of mass at least one half increases the +probability of any event by at most a factor of two. -/ +theorem probability_subtype_le_two (A H : Set Ω) [Fintype H] + (hH : (1 / 2 : ℝ) ≤ probability H) : + probability {x : H | x.val ∈ A} ≤ 2 * probability A := by + rw [probability_subtype] + apply (div_le_iff₀ (by linarith : 0 < probability H)).mpr + have hi : probability (A ∩ H) ≤ probability A := probability_mono Set.inter_subset_left + have hm := mul_le_mul_of_nonneg_left hH (probability_nonneg A) + nlinarith + +end Conditioning + +/-- In the actual uniform full-rank matrix sample space, restricted rank +failure costs at most twice the unrestricted rank-failure estimate. -/ +theorem full_rank_restricted_failure_probability_le (T : Finset ι) + (hfull : (1 / 2 : ℝ) ≤ probability {B : BinaryMatrix ι r | FullRowRank B}) : + probability {B : FullRankMatrix ι r | + ¬ Function.Surjective (restrictedMap B.val T (K := ZMod 2))} ≤ + 2 * (((2 ^ r - 1 : ℕ) : ℝ) * (1 / 2 : ℝ) ^ T.card) := by + calc + _ ≤ 2 * probability {B : BinaryMatrix ι r | + ¬ Function.Surjective (restrictedMap B T (K := ZMod 2))} := + probability_subtype_le_two _ _ hfull + _ ≤ _ := by gcongr; exact restricted_failure_probability_le T + +/-- The numerical rank-error hypothesis guarantees that the conditioning +event has mass at least one half. -/ +theorem half_le_full_rank_probability + (h : ((2 ^ r - 1 : ℕ) : ℝ) * (1 / 2 : ℝ) ^ Fintype.card ι ≤ 1 / 2) : + (1 / 2 : ℝ) ≤ probability {B : BinaryMatrix ι r | FullRowRank B} := by + have hl := full_rank_probability_ge (ι := ι) (r := r) + linarith + +/-- A positive full-rank mass gives an actual full-rank matrix. -/ +theorem nonempty_fullRankMatrix + (h : 0 < probability {B : BinaryMatrix ι r | FullRowRank B}) : + Nonempty (FullRankMatrix ι r) := by + have hc := probability_compl {B : BinaryMatrix ι r | FullRowRank B} + have hb : probability ({B : BinaryMatrix ι r | FullRowRank B}ᶜ) < 1 := by linarith + obtain ⟨B, hB⟩ := exists_not_mem_of_probability_lt_one _ hb + exact ⟨B, by simpa using hB⟩ + +/-- The rank-error expression loses one factor `2` per extra column, +uniformly in the number of rows. -/ +theorem rank_error_le_pow (r n k : ℕ) (h : r + k ≤ n) : + ((2 ^ r - 1 : ℕ) : ℝ) * (1 / 2 : ℝ) ^ n ≤ (1 / 2 : ℝ) ^ k := by + have hc : ((2 ^ r - 1 : ℕ) : ℝ) ≤ (2 : ℝ) ^ r := by + exact_mod_cast Nat.sub_le (2 ^ r) 1 + calc + _ ≤ (2 : ℝ) ^ r * (1 / 2 : ℝ) ^ n := + mul_le_mul_of_nonneg_right hc (by positivity) + _ ≤ (2 : ℝ) ^ r * (1 / 2 : ℝ) ^ (r + k) := + mul_le_mul_of_nonneg_left + (pow_le_pow_of_le_one (by norm_num) (by norm_num) h) (by positivity) + _ = _ := by rw [pow_add, ← mul_assoc, ← mul_pow]; norm_num + +/-- One more column than rows suffices for full-rank mass at least one half. -/ +theorem half_le_full_rank_probability_of_card (hm : r + 1 ≤ Fintype.card ι) : + (1 / 2 : ℝ) ≤ probability {B : BinaryMatrix ι r | FullRowRank B} := by + apply half_le_full_rank_probability + simpa using rank_error_le_pow r (Fintype.card ι) 1 hm + +omit [DecidableEq ι] in +/-- The full-rank matrix sample type is inhabited under the usual spare-column +condition. This supplies a genuine uniform finite experiment. -/ +theorem nonempty_fullRankMatrix_of_card (hm : r + 1 ≤ Fintype.card ι) : + Nonempty (FullRankMatrix ι r) := by + classical + apply nonempty_fullRankMatrix + have h := half_le_full_rank_probability_of_card hm + linarith + +/-- With at least twice as many selected columns as rows, the full-rank +conditioned restriction fails with probability at most `2 * 2^(-r)`. -/ +theorem full_rank_restricted_failure_probability_le_pow (T : Finset ι) + (hfull : (1 / 2 : ℝ) ≤ probability {B : BinaryMatrix ι r | FullRowRank B}) + (hT : 2 * r ≤ T.card) : + probability {B : FullRankMatrix ι r | + ¬ Function.Surjective (restrictedMap B.val T (K := ZMod 2))} ≤ + 2 * (1 / 2 : ℝ) ^ r := by + calc + _ ≤ 2 * (((2 ^ r - 1 : ℕ) : ℝ) * (1 / 2 : ℝ) ^ T.card) := + full_rank_restricted_failure_probability_le T hfull + _ ≤ _ := mul_le_mul_of_nonneg_left (rank_error_le_pow r T.card r (by omega)) + (by norm_num) + +omit [DecidableEq ι] in +/-- A version whose hypotheses are entirely column-count inequalities. -/ +theorem full_rank_restricted_failure_probability_le_pow_of_card (T : Finset ι) + (hm : r + 1 ≤ Fintype.card ι) (hT : 2 * r ≤ T.card) : + probability {B : FullRankMatrix ι r | + ¬ Function.Surjective (restrictedMap B.val T (K := ZMod 2))} ≤ + 2 * (1 / 2 : ℝ) ^ r := by + classical + exact full_rank_restricted_failure_probability_le_pow T + (half_le_full_rank_probability_of_card hm) hT + +end Klr.RandomMatrix diff --git a/LeanPool/KLRandomness/RandomMatrixAlgebra.lean b/LeanPool/KLRandomness/RandomMatrixAlgebra.lean new file mode 100644 index 0000000000..6830875960 --- /dev/null +++ b/LeanPool/KLRandomness/RandomMatrixAlgebra.lean @@ -0,0 +1,116 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.Affine +public import Mathlib.LinearAlgebra.Dual.Lemmas + +/-! +# The algebraic obstruction to full row rank + +A matrix is represented by its finite family of columns. Its row rank is +full exactly when no nonzero linear functional annihilates all the columns. +The evaluation map for a fixed nonzero functional is surjective on every +set of columns. These facts supply the algebraic part of the random-matrix +estimate used in the finite candidate construction. +-/ + +@[expose] public section + +namespace Klr.RandomMatrix + +open scoped BigOperators + +variable {K V ι : Type*} [Field K] [AddCommGroup V] [Module K V] + [Fintype ι] + +/-- The linear map whose columns are the vectors `B i`. -/ +noncomputable def columnMap (B : ι → V) : (ι → K) →ₗ[K] V where + toFun x := ∑ i, x i • B i + map_add' x y := by simp [add_smul, Finset.sum_add_distrib] + map_smul' a x := by simp [mul_smul, Finset.smul_sum] + +@[simp] theorem columnMap_apply (B : ι → V) (x : ι → K) : + columnMap B x = ∑ i, x i • B i := rfl + +theorem columnMap_single [DecidableEq ι] (B : ι → V) (i : ι) : + columnMap B (Pi.single i (1 : K)) = B i := by + simp [columnMap, Pi.single_apply] + +theorem column_mem_range (B : ι → V) (i : ι) : + B i ∈ LinearMap.range (columnMap B (K := K)) := by + classical + exact ⟨Pi.single i 1, columnMap_single B i⟩ + +/-- Failure of full row rank is witnessed by a nonzero row functional. -/ +theorem not_surjective_iff_exists_annihilator (B : ι → V) : + ¬ Function.Surjective (columnMap B (K := K)) ↔ + ∃ φ : Module.Dual K V, φ ≠ 0 ∧ ∀ i, φ (B i) = 0 := by + constructor + · intro hB + have hr : LinearMap.range (columnMap B (K := K)) < ⊤ := by + exact lt_top_iff_ne_top.mpr (fun h => hB (LinearMap.range_eq_top.mp h)) + obtain ⟨φ, hφ, hrφ⟩ := + Submodule.exists_dual_map_eq_bot_of_lt_top hr inferInstance + refine ⟨φ, hφ, fun i => ?_⟩ + have hi : φ (B i) ∈ (LinearMap.range (columnMap B (K := K))).map φ := + ⟨B i, column_mem_range B i, rfl⟩ + rwa [hrφ, Submodule.mem_bot] at hi + · rintro ⟨φ, hφ, hB⟩ hs + apply hφ + ext v + obtain ⟨x, rfl⟩ := hs v + simp [columnMap, map_sum, hB] + +/-- Apply one row functional to each column in a fixed finite set. -/ +noncomputable def evaluationMap (φ : Module.Dual K V) (T : Finset ι) : + (ι → V) →ₗ[K] (T → K) where + toFun B t := φ (B t.val) + map_add' B C := by ext t; simp + map_smul' a B := by ext t; simp + +omit [Fintype ι] in +@[simp] theorem evaluationMap_apply (φ : Module.Dual K V) (T : Finset ι) + (B : ι → V) (t : T) : evaluationMap φ T B t = φ (B t.val) := rfl + +omit [Fintype ι] in +/-- A nonzero scalar-valued functional produces every requested pattern of +values on the selected columns. -/ +theorem evaluationMap_surjective {φ : Module.Dual K V} (hφ : φ ≠ 0) + (T : Finset ι) : Function.Surjective (evaluationMap φ T) := by + classical + obtain ⟨u, hu⟩ := (LinearMap.surjective hφ) 1 + intro y + refine ⟨fun i => if hi : i ∈ T then y ⟨i, hi⟩ • u else 0, ?_⟩ + ext t + simp [evaluationMap, t.property, hu] + +/-- The restriction of a matrix to the columns in `T`. -/ +noncomputable def restrictedMap (B : ι → V) (T : Finset ι) : (T → K) →ₗ[K] V := + columnMap (fun t : T => B t.val) + +omit [Fintype ι] in +theorem restricted_not_surjective_iff (B : ι → V) (T : Finset ι) : + ¬ Function.Surjective (restrictedMap B T (K := K)) ↔ + ∃ φ : Module.Dual K V, φ ≠ 0 ∧ evaluationMap φ T B = 0 := by + rw [restrictedMap, not_surjective_iff_exists_annihilator] + constructor + · rintro ⟨φ, hφ, hB⟩ + exact ⟨φ, hφ, funext hB⟩ + · rintro ⟨φ, hφ, hB⟩ + exact ⟨φ, hφ, fun t => congrFun hB t⟩ + +theorem restricted_univ_surjective_iff (B : ι → V) : + Function.Surjective (restrictedMap B Finset.univ (K := K)) ↔ + Function.Surjective (columnMap B (K := K)) := by + rw [← not_iff_not, restricted_not_surjective_iff, + not_surjective_iff_exists_annihilator] + simp [evaluationMap, funext_iff] + +end Klr.RandomMatrix diff --git a/LeanPool/KLRandomness/RemainingRank.lean b/LeanPool/KLRandomness/RemainingRank.lean new file mode 100644 index 0000000000..10bb5c0f42 --- /dev/null +++ b/LeanPool/KLRandomness/RemainingRank.lean @@ -0,0 +1,220 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.StoppingTranscript + +/-! +# Numerical remaining rank and the first rank-drop event + +The remaining rank is the dimension of the image of the unread-column map. +It can only decrease as more coordinates are queried. Its initial value is +the block's row rank, so the first loss of surjectivity is exactly the first +strict numerical rank decrease. + +The final event uses the paper's one-based query numbering: a drop at query +`t` compares the ranks after `t` and `t - 1` answers. Thus a drop after horizon +`N` has a pre-drop transcript of length at least `N`. +-/ + +@[expose] public section + +namespace Klr + +open AffineObservation + +namespace AffineObservation + +/-- Observing more coordinates can only shrink the remaining-column image. -/ +theorem unreadMap_range_antitone {ι : Type*} {r : ℕ} + (D : (ι → ZMod 2) →ₗ[ZMod 2] (Fin r → ZMod 2)) + {O P : Set ι} [DecidablePred (· ∈ O)] [DecidablePred (· ∈ P)] + (hOP : O ⊆ P) : + LinearMap.range (unreadMap D P) ≤ LinearMap.range (unreadMap D O) := by + rintro y ⟨u, rfl⟩ + refine ⟨unreadPart O (extendUnread P u), ?_⟩ + change D (extendUnread O (unreadPart O (extendUnread P u))) = D (extendUnread P u) + congr 1 + apply extendUnread_unreadPart_of_observed_zero + funext i + simp [observedPart, extendUnread, hOP i.property] + +end AffineObservation + +namespace ScanRule + +/-- Extending a transcript retains every previously queried position. -/ +theorem queriedPositions_mono (π : ScanRule) {u v : List Bool} (h : u <+: v) : + π.queriedPositions u ⊆ π.queriedPositions v := by + rintro q hq + obtain ⟨i, _, rfl⟩ := Finset.mem_image.mp hq + let j : Fin v.length := ⟨i.val, lt_of_lt_of_le i.isLt h.length_le⟩ + refine Finset.mem_image.mpr ⟨j, Finset.mem_univ _, ?_⟩ + change π.query (v.take i.val) = π.query (u.take i.val) + rcases h with ⟨w, rfl⟩ + rw [List.take_append_of_le_length i.isLt.le] + +end ScanRule + +namespace AffineBlock + +/-- The dimension of the image of the block's unread-column map. -/ +noncomputable def remainingRank (B : AffineBlock) (π : ScanRule) (v : List Bool) : ℕ := + Module.finrank (ZMod 2) (LinearMap.range (unreadMap B.matrix (B.observed π v))) + +/-- Full unread row rank is exactly equality with the block's initial row rank. -/ +theorem unreadFullRank_iff_remainingRank (B : AffineBlock) (π : ScanRule) + (v : List Bool) : B.UnreadFullRank π v ↔ B.remainingRank π v = B.rank := by + change Function.Surjective (unreadMap B.matrix (B.observed π v)) ↔ _ + rw [← LinearMap.range_eq_top] + constructor + · intro h + change Module.finrank (ZMod 2) + (LinearMap.range (unreadMap B.matrix (B.observed π v))) = B.rank + rw [h, finrank_top] + simp + · intro h + apply Submodule.eq_top_of_finrank_eq + simpa [remainingRank] using h + +/-- The unread image never has dimension larger than the row space. -/ +theorem remainingRank_le (B : AffineBlock) (π : ScanRule) (v : List Bool) : + B.remainingRank π v ≤ B.rank := by + simpa [remainingRank] using + Submodule.finrank_le (LinearMap.range (unreadMap B.matrix (B.observed π v))) + +@[simp] theorem remainingRank_nil (B : AffineBlock) (π : ScanRule) : + B.remainingRank π [] = B.rank := + (B.unreadFullRank_iff_remainingRank π []).mp (B.unreadFullRank_nil π) + +/-- Remaining rank is antitone in the set of positions already queried. -/ +theorem remainingRank_le_of_queriedPositions_subset (B : AffineBlock) (π : ScanRule) + {u v : List Bool} (h : π.queriedPositions u ⊆ π.queriedPositions v) : + B.remainingRank π v ≤ B.remainingRank π u := by + apply Submodule.finrank_mono + apply unreadMap_range_antitone + intro i hi + exact h hi + +/-- Remaining rank can only decrease along an extending transcript. -/ +theorem remainingRank_antitone_prefix (B : AffineBlock) (π : ScanRule) + {u v : List Bool} (h : u <+: v) : + B.remainingRank π v ≤ B.remainingRank π u := + B.remainingRank_le_of_queriedPositions_subset π (π.queriedPositions_mono h) + +/-- Remaining rank is a nonincreasing sequence along every input. -/ +theorem remainingRank_transcript_antitone (B : AffineBlock) (π : ScanRule) (X : Cantor) : + Antitone (fun n => B.remainingRank π (π.transcript X n)) := + fun _ _ h => B.remainingRank_antitone_prefix π (π.transcript_prefix X h) + +/-- Before the first strict decrease, the numerical rank is still its initial value. -/ +theorem remainingRank_eq_rank_of_no_drop (B : AffineBlock) (π : ScanRule) + (X : Cantor) (n : ℕ) + (h : ∀ k < n, ¬B.remainingRank π (π.transcript X (k + 1)) < + B.remainingRank π (π.transcript X k)) : + B.remainingRank π (π.transcript X n) = B.rank := by + induction n with + | zero => simp + | succ n ih => + have hn := ih (fun k hk => h k (by omega)) + have hle := B.remainingRank_transcript_antitone π X (Nat.le_succ n) + have hge := Nat.le_of_not_gt (h n (Nat.lt_succ_self n)) + exact (le_antisymm hle hge).trans hn + +end AffineBlock + +namespace StoppingTranscript + +open MeasureTheory ProbabilityTheory + +/-- The predictable trigger occurs exactly before the first strict numerical rank drop. -/ +theorem rankDropTrigger_iff_first_rank_drop (B : AffineBlock) (π : ScanRule) + (X : Cantor) (n : ℕ) : + rankDropTrigger B π (π.transcript X n) ↔ + B.remainingRank π (π.transcript X (n + 1)) < B.remainingRank π (π.transcript X n) ∧ + ∀ k < n, ¬B.remainingRank π (π.transcript X (k + 1)) < + B.remainingRank π (π.transcript X k) := by + rw [rankDropTrigger_transcript_iff, + B.unreadFullRank_iff_remainingRank, B.unreadFullRank_iff_remainingRank] + constructor + · rintro ⟨hn, hn1⟩ + have hbefore : ∀ k ≤ n, B.remainingRank π (π.transcript X k) = B.rank := by + intro k hk + apply le_antisymm (B.remainingRank_le π _) + rw [← hn] + exact B.remainingRank_transcript_antitone π X hk + constructor + · rw [hn] + exact lt_of_le_of_ne (B.remainingRank_le π _) hn1 + · intro k hk + rw [hbefore k hk.le, hbefore (k + 1) (by omega)] + exact lt_irrefl _ + · rintro ⟨hdrop, hfirst⟩ + have hn := B.remainingRank_eq_rank_of_no_drop π X n hfirst + refine ⟨hn, ?_⟩ + intro hn1 + rw [hn, hn1] at hdrop + exact lt_irrefl _ hdrop + +/-- The stopping event is exactly the first strict numerical rank decrease after `N`. +The witness `t` is a one-based query number, as in the paper. -/ +theorem mem_rankDropTailEvent_iff_remainingRank (B : AffineBlock) (π : ScanRule) + (N : ℕ) (X : Cantor) : + X ∈ rankDropTailEvent B π N ↔ + ∃ t, N < t ∧ + B.remainingRank π (π.transcript X t) < B.remainingRank π (π.transcript X (t - 1)) ∧ + ∀ s, 0 < s → s < t → + ¬B.remainingRank π (π.transcript X s) < + B.remainingRank π (π.transcript X (s - 1)) := by + rw [← unionEvent_rankDropTriggerTail, mem_unionEvent_firstTriggerTail_iff] + constructor + · rintro ⟨n, hN, htrigger, _⟩ + obtain ⟨hdrop, hfirst⟩ := (rankDropTrigger_iff_first_rank_drop B π X n).mp htrigger + refine ⟨n + 1, by omega, by simpa using hdrop, ?_⟩ + intro s hs hsn + obtain ⟨k, rfl⟩ := Nat.exists_eq_succ_of_ne_zero (show s ≠ 0 by omega) + simpa using hfirst k (by omega) + · rintro ⟨t, hN, hdrop, hfirst⟩ + obtain ⟨n, rfl⟩ := Nat.exists_eq_succ_of_ne_zero (show t ≠ 0 by omega) + simp only [Nat.succ_sub_one] at hdrop + have hfirst' : ∀ k < n, ¬B.remainingRank π (π.transcript X (k + 1)) < + B.remainingRank π (π.transcript X k) := by + intro k hk + simpa using hfirst (k + 1) (by omega) (by omega) + refine ⟨n, by omega, + (rankDropTrigger_iff_first_rank_drop B π X n).mpr ⟨hdrop, hfirst'⟩, ?_⟩ + intro k hk htrigger + exact hfirst' k hk ((rankDropTrigger_iff_first_rank_drop B π X k).mp htrigger).1 + +/-- The event `N < T < ∞`, where `T` is the first strict numerical rank-drop query. -/ +def strictRankDropTailEvent (B : AffineBlock) (π : ScanRule) (N : ℕ) : Set Cantor := + {X | ∃ t, N < t ∧ + B.remainingRank π (π.transcript X t) < B.remainingRank π (π.transcript X (t - 1)) ∧ + ∀ s, 0 < s → s < t → + ¬B.remainingRank π (π.transcript X s) < B.remainingRank π (π.transcript X (s - 1))} + +theorem rankDropTailEvent_eq_strictRankDropTailEvent (B : AffineBlock) + (π : ScanRule) (N : ℕ) : + rankDropTailEvent B π N = strictRankDropTailEvent B π N := by + ext X + exact mem_rankDropTailEvent_iff_remainingRank B π N X + +/-- Adding a disjoint full-rank block preserves the tail distribution of the actual +first strict rank decrease, with the paper's one-based query indexing. -/ +theorem nextStage_strictRankDropTail {κ : Type*} [Finite κ] + (old : κ → AffineBlock) (B : AffineBlock) + (hold : Pairwise (fun i j => Disjoint (old i).support (old j).support)) + (hnew : ∀ k, Disjoint (old k).support B.support) (π : ScanRule) (N : ℕ) : + (cond fairCoin (AffineBlock.familyEvent old ∩ B.event)) (strictRankDropTailEvent B π N) = + (AffineBlock.finiteStageLaw old) (strictRankDropTailEvent B π N) := by + rw [← rankDropTailEvent_eq_strictRankDropTailEvent] + exact nextStage_rankDropTail old B hold hnew π N + +end StoppingTranscript +end Klr diff --git a/LeanPool/KLRandomness/SampleConcentration.lean b/LeanPool/KLRandomness/SampleConcentration.lean new file mode 100644 index 0000000000..dcf2d9a8e2 --- /dev/null +++ b/LeanPool/KLRandomness/SampleConcentration.lean @@ -0,0 +1,193 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.FiniteProbability +public import Mathlib.Analysis.SpecialFunctions.Log.Basic +import Mathlib.Tactic.Linarith +import Mathlib.Tactic.NormNum +import Mathlib.Tactic.Positivity + +/-! +# Concentration of independent finite samples + +The exponential moments here are identities for actual uniformly sampled finite +lists. Markov's inequality then supplies the two tail estimates used for sparse +candidate lists. Slightly weaker rational exponents simplify the constants in +the paper without changing the eventual parameter regime. +-/ + +@[expose] public section + +namespace Klr.SampleConcentration + +open scoped BigOperators +open FiniteProbability + +variable {Ω : Type*} [Fintype Ω] [Nonempty Ω] + +/-- The number of samples belonging to an event. -/ +noncomputable def count {J : ℕ} (A : Set Ω) (z : Fin J → Ω) : ℕ := by + classical + exact (Finset.univ.filter fun i => z i ∈ A).card + +/-- The exact probability generating function of the count of independent samples. -/ +theorem average_pow_count (A : Set Ω) (J : ℕ) (b : ℝ) : + average (fun z : Fin J → Ω => b ^ count A z) = + (1 + (b - 1) * probability A) ^ J := by + classical + calc + average (fun z : Fin J → Ω => b ^ count A z) = + average (fun z : Fin J → Ω => ∏ i, if z i ∈ A then b else 1) := by + apply average_congr + intro z + simp [count, Finset.prod_ite] + _ = (average (fun x => if x ∈ A then b else 1)) ^ J := by + simpa using average_prod_samples (fun x : Ω => if x ∈ A then b else 1) J + _ = (1 + (b - 1) * probability A) ^ J := by + congr 1 + calc + average (fun x => if x ∈ A then b else 1) = + average (fun x => 1 + (b - 1) * (if x ∈ A then (1 : ℝ) else 0)) := by + apply average_congr + intro x + by_cases hx : x ∈ A <;> simp [hx] + _ = 1 + (b - 1) * probability A := by + rw [average_add, average_const, average_const_mul] + rfl + +/-- Exponential-moment tail bound for any base greater than one. -/ +theorem probability_count_gt_le (A : Set Ω) (J : ℕ) (b : ℝ) (hb : 1 < b) + (t : ℝ) : + probability {z : Fin J → Ω | t < (count A z : ℝ)} ≤ + Real.exp ((b - 1) * probability A * J - Real.log b * t) := by + have hb0 : 0 < b := lt_trans zero_lt_one hb + have hlog : 0 ≤ Real.log b := Real.log_nonneg (le_of_lt hb) + have hpn : 0 ≤ probability A := probability_nonneg A + have hbn : 0 ≤ b - 1 := sub_nonneg.mpr (le_of_lt hb) + have hmoment : average (fun z : Fin J → Ω => b ^ count A z) ≤ + Real.exp ((b - 1) * probability A * J) := by + rw [average_pow_count] + calc + (1 + (b - 1) * probability A) ^ J ≤ + (Real.exp ((b - 1) * probability A)) ^ J := by + apply pow_le_pow_left₀ (by positivity) + simpa only [add_comm] using Real.add_one_le_exp ((b - 1) * probability A) + _ = Real.exp ((b - 1) * probability A * J) := by + rw [← Real.exp_nat_mul, mul_comm] + calc + probability {z : Fin J → Ω | t < (count A z : ℝ)} ≤ + probability {z : Fin J → Ω | + Real.exp (Real.log b * t) ≤ b ^ count A z} := by + apply probability_mono + intro z hz + change Real.exp (Real.log b * t) ≤ b ^ count A z + calc + Real.exp (Real.log b * t) ≤ Real.exp ((count A z : ℝ) * Real.log b) := by + apply Real.exp_le_exp.mpr + nlinarith [show t < (count A z : ℝ) from hz] + _ = b ^ count A z := by rw [Real.exp_nat_mul, Real.exp_log hb0] + _ ≤ average (fun z : Fin J → Ω => b ^ count A z) / + Real.exp (Real.log b * t) := + probability_le_average_div _ (fun _ => pow_nonneg (le_of_lt hb0) _) + _ (Real.exp_pos _) + _ ≤ Real.exp ((b - 1) * probability A * J) / Real.exp (Real.log b * t) := + div_le_div_of_nonneg_right hmoment (le_of_lt (Real.exp_pos _)) + _ = Real.exp ((b - 1) * probability A * J - Real.log b * t) := + (Real.exp_sub _ _).symm + +/-- A rare bad-rank event occurs in at most a `θ` fraction of the samples, +outside an exceptional set of probability at most `exp (-θ J / 4)`. -/ +theorem rank_tail (A : Set Ω) (J : ℕ) (θ : ℝ) (hθ : 0 ≤ θ) + (hp : probability A ≤ θ / 4) : + probability {z : Fin J → Ω | θ * J < (count A z : ℝ)} ≤ + Real.exp (-(θ * J) / 4) := by + have hl : (1 / 2 : ℝ) ≤ Real.log 2 := by + have h := Real.one_sub_inv_le_log_of_pos (show (0 : ℝ) < 2 by norm_num) + norm_num at h + linarith + calc + probability {z : Fin J → Ω | θ * J < (count A z : ℝ)} ≤ + Real.exp ((2 - 1) * probability A * J - Real.log 2 * (θ * J)) := + probability_count_gt_le A J 2 (by norm_num) _ + _ ≤ Real.exp (-(θ * J) / 4) := by + apply Real.exp_le_exp.mpr + have hJ : (0 : ℝ) ≤ J := Nat.cast_nonneg _ + have h1 := mul_le_mul_of_nonneg_right hp hJ + have h2 := mul_le_mul_of_nonneg_right hl (mul_nonneg hθ hJ) + nlinarith + +/-- Twice the marginal incidence is enough for simultaneous sparse supports. +Base `3/2` gives a convenient rational exponential bound. -/ +theorem incidence_tail (A : Set Ω) (J : ℕ) (p : ℝ) (hp0 : 0 ≤ p) + (hp : probability A ≤ p) : + probability {z : Fin J → Ω | 2 * p * J < (count A z : ℝ)} ≤ + Real.exp (-(p * J) / 6) := by + have hl : (1 / 3 : ℝ) ≤ Real.log (3 / 2) := by + have h := Real.one_sub_inv_le_log_of_pos (show (0 : ℝ) < 3 / 2 by norm_num) + norm_num at h + linarith + calc + probability {z : Fin J → Ω | 2 * p * J < (count A z : ℝ)} ≤ + Real.exp ((3 / 2 - 1) * probability A * J - Real.log (3 / 2) * (2 * p * J)) := + probability_count_gt_le A J (3 / 2) (by norm_num) _ + _ ≤ Real.exp (-(p * J) / 6) := by + apply Real.exp_le_exp.mpr + have hJ : (0 : ℝ) ≤ J := Nat.cast_nonneg _ + have h1 := mul_le_mul_of_nonneg_right hp hJ + have h2 := mul_le_mul_of_nonneg_right hl (by positivity : 0 ≤ 2 * p * J) + nlinarith + +/-- A single finite list simultaneously controls all events in both families. +The hypotheses refer to their actual marginal probabilities. -/ +theorem exists_simultaneous_samples {α β : Type*} [Fintype α] [Fintype β] + (A : α → Set Ω) (B : β → Set Ω) (J : ℕ) (θ p : ℝ) + (hθ : 0 ≤ θ) (hp0 : 0 ≤ p) + (hA : ∀ a, probability (A a) ≤ θ / 4) + (hB : ∀ b, probability (B b) ≤ p) + (hsmall : Fintype.card α * Real.exp (-(θ * J) / 4) + + Fintype.card β * Real.exp (-(p * J) / 6) < 1) : + ∃ z : Fin J → Ω, + (∀ a, (count (A a) z : ℝ) ≤ θ * J) ∧ + (∀ b, (count (B b) z : ℝ) ≤ 2 * p * J) := by + classical + let E : α ⊕ β → Set (Fin J → Ω) := Sum.elim + (fun a => {z | θ * J < (count (A a) z : ℝ)}) + (fun b => {z | 2 * p * J < (count (B b) z : ℝ)}) + have he : probability (⋃ i, E i) < 1 := by + calc + probability (⋃ i, E i) ≤ ∑ i, probability (E i) := probability_iUnion_le E + _ = (∑ a, probability {z : Fin J → Ω | θ * J < (count (A a) z : ℝ)}) + + ∑ b, probability {z : Fin J → Ω | 2 * p * J < (count (B b) z : ℝ)} := by + rw [Fintype.sum_sum_type] + rfl + _ ≤ Fintype.card α * Real.exp (-(θ * J) / 4) + + Fintype.card β * Real.exp (-(p * J) / 6) := by + apply add_le_add + · calc + _ ≤ ∑ _a : α, Real.exp (-(θ * J) / 4) := + Finset.sum_le_sum fun a _ => rank_tail (A a) J θ hθ (hA a) + _ = _ := by simp + · calc + _ ≤ ∑ _b : β, Real.exp (-(p * J) / 6) := + Finset.sum_le_sum fun b _ => incidence_tail (B b) J p hp0 (hB b) + _ = _ := by simp + _ < 1 := hsmall + obtain ⟨z, hz⟩ := exists_not_mem_of_probability_lt_one (⋃ i, E i) he + refine ⟨z, ?_, ?_⟩ + · intro a + apply le_of_not_gt + intro ha + exact hz (Set.mem_iUnion.mpr ⟨Sum.inl a, ha⟩) + · intro b + apply le_of_not_gt + intro hb + exact hz (Set.mem_iUnion.mpr ⟨Sum.inr b, hb⟩) + +end Klr.SampleConcentration diff --git a/LeanPool/KLRandomness/ScanMeasure.lean b/LeanPool/KLRandomness/ScanMeasure.lean new file mode 100644 index 0000000000..895f44220d --- /dev/null +++ b/LeanPool/KLRandomness/ScanMeasure.lean @@ -0,0 +1,118 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.Betting +public import Mathlib.Probability.Independence.InfinitePi +public import Mathlib.Data.List.GetD +public import Mathlib.Data.List.TakeDrop +import Mathlib.Tactic.FunProp + +/-! +# Fair-coin law of adaptive transcripts + +For a fixed finite transcript, all of its query positions are already determined. +Freshness makes those positions distinct. The input event producing that transcript +is therefore a finite assignment of independent fair bits, even though the scan +rule chooses positions adaptively on other transcripts. +-/ + +@[expose] public section + +namespace Klr.ScanRule + +open MeasureTheory +open scoped ENNReal + +/-- Distinct prefixes of a fixed transcript query different input positions. -/ +theorem query_take_ne (π : ScanRule) (v : List Bool) {m n : ℕ} + (hmn : m < n) (hn : n ≤ v.length) : + π.query (v.take m) ≠ π.query (v.take n) := by + have hlen : (v.take n).length = n := by simp [List.length_take, hn] + have h := π.fresh (v.take n) m (by rw [hlen]; exact hmn) + simpa [List.take_take, Nat.min_eq_left hmn.le] using h + +/-- The fixed coordinates specified by a finite transcript form an injection. -/ +theorem query_take_injective (π : ScanRule) (v : List Bool) : + Function.Injective (fun i : Fin v.length => π.query (v.take i.val)) := by + intro i j h + apply Fin.ext + rcases lt_trichotomy i.val j.val with hij | hij | hij + · exact False.elim (π.query_take_ne v hij j.isLt.le h) + · exact hij + · exact False.elim (π.query_take_ne v hij i.isLt.le h.symm) + +/-- The bit at transcript index `i` is the answer to the query chosen after `i` steps. -/ +theorem getD_transcript (π : ScanRule) (X : Cantor) {n i : ℕ} (hi : i < n) : + (π.transcript X n).getD i false = X (π.query (π.transcript X i)) := by + induction n generalizing i with + | zero => omega + | succ n ih => + rcases lt_or_eq_of_le (Nat.le_of_lt_succ hi) with hlt | rfl + · rw [transcript_succ, List.getD_append _ _ _ _ (by simpa using hlt)] + exact ih hlt + · rw [transcript_succ, List.getD_append_right _ _ _ _ (by simp)] + simp + +/-- Agreement with the finite assignment encoded by a transcript reconstructs every prefix. -/ +theorem transcript_eq_take_of_agrees (π : ScanRule) (X : Cantor) (v : List Bool) + (hX : ∀ i < v.length, X (π.query (v.take i)) = v.getD i false) + {n : ℕ} (hn : n ≤ v.length) : π.transcript X n = v.take n := by + induction n with + | zero => simp + | succ n ih => + have hlt : n < v.length := lt_of_lt_of_le (Nat.lt_succ_self n) hn + rw [transcript_succ, ih (Nat.le_of_succ_le hn), hX n hlt, + List.getD_eq_getElem _ _ hlt] + exact List.take_concat_get' v n hlt + +/-- Adaptive transcript preimages are exactly finite assignments to the queried coordinates. -/ +theorem transcript_eq_iff (π : ScanRule) (X : Cantor) (v : List Bool) : + π.transcript X v.length = v ↔ + ∀ i < v.length, X (π.query (v.take i)) = v.getD i false := by + constructor + · intro h i hi + have ht : π.transcript X i = v.take i := by + rw [← h, π.transcript_take X hi.le] + rw [← ht, ← π.getD_transcript X hi, h] + · intro h + simpa using π.transcript_eq_take_of_agrees X v h le_rfl + +/-- The transcript event is the preimage of one fixed finite assignment. -/ +theorem transcript_event_eq_preimage (π : ScanRule) (v : List Bool) : + {X : Cantor | π.transcript X v.length = v} = + (fun X : Cantor => fun i : Fin v.length => X (π.query (v.take i.val))) ⁻¹' + {fun i : Fin v.length => v.getD i.val false} := by + ext X + simp only [Set.mem_ofPred_eq, Set.mem_preimage, Set.mem_singleton_iff, funext_iff] + rw [transcript_eq_iff] + exact ⟨fun h i => h i.val i.isLt, fun h i hi => h ⟨i, hi⟩⟩ + +/-- The event of observing a prescribed finite transcript is measurable. -/ +theorem measurableSet_transcript (π : ScanRule) (v : List Bool) : + MeasurableSet {X | π.transcript X v.length = v} := by + rw [transcript_event_eq_preimage] + exact (by fun_prop : Measurable (fun X : Cantor => fun i : Fin v.length => + X (π.query (v.take i.val)))) (measurableSet_singleton _) + +/-- A finite transcript has exactly the same probability as a fair bit string. -/ +theorem fairCoin_transcript (π : ScanRule) (v : List Bool) : + fairCoin {X | π.transcript X v.length = v} = (1 / 2 : ℝ≥0∞) ^ v.length := by + rw [transcript_event_eq_preimage] + let f : Cantor → (Fin v.length → Bool) := fun X i => X (π.query (v.take i.val)) + let bits : Fin v.length → Bool := fun i => v.getD i.val false + change fairCoin (f ⁻¹' {bits}) = _ + have hf : Measurable f := by fun_prop + rw [← Measure.map_apply hf (measurableSet_singleton bits)] + change (Measure.infinitePi (fun _ : ℕ => fairBit)).map f {bits} = _ + rw [Measure.map_infinitePi_infinitePi_of_inj (π.query_take_injective v)] + rw [Measure.infinitePi_eq_pi, Measure.pi_singleton] + simp + +end Klr.ScanRule diff --git a/LeanPool/KLRandomness/Separation.lean b/LeanPool/KLRandomness/Separation.lean new file mode 100644 index 0000000000..29fe7c57ed --- /dev/null +++ b/LeanPool/KLRandomness/Separation.lean @@ -0,0 +1,65 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.StageConstruction +public import LeanPool.KLRandomness.StageEnumeration +public import LeanPool.KLRandomness.MLImpliesKL +public import LeanPool.KLRandomness.PartialBettingCapital + +/-! +# Separation for the total computable-real strategy convention + +The completed stage construction supplies all analytic estimates and all +actual short affine programs. A classical enumeration covers every strategy +in the repository's total computable-real `BettingStrategy` type. Thus the +separation below has no construction or description premise. + +The theorem uses the repository's explicit total-strategy convention. It +does not assert a new equivalence with a general partial computable-real +strategy convention. +-/ + +@[expose] public section + +namespace Klr + +/-- There is a sequence which defeats every total computable-real +Kolmogorov–Loveland betting strategy but fails a Martin-Löf test. -/ +theorem exists_kolmogorovLovelandRandom_not_martinLofRandom : + ∃ X : Cantor, KolmogorovLovelandRandom X ∧ ¬MartinLofRandom X := by + obtain ⟨s, hs⟩ := StageEnumeration.exists_surjective + obtain ⟨H, hH, hstep⟩ := StageConstruction.exists_fixed_partitions_steps s + exact StageRecursion.exists_separating_of_steps s H hstep hs hH + +/-- The same witness also defeats every infinite fresh run of an actual +partial rational-wager source program, by the proved even/odd totalization. -/ +theorem exists_not_martinLofRandom_no_partial_rational_success : + ∃ X : Cantor, ¬MartinLofRandom X ∧ + ∀ (c : Nat.Partrec.Code) (r : PartialBetting.SourceRun c X), ¬r.Succeeds := by + obtain ⟨X, hKL, hML⟩ := exists_kolmogorovLovelandRandom_not_martinLofRandom + exact ⟨X, hML, fun _ r => PartialBetting.no_partial_rational_success hKL r⟩ + +/-- Martin-Löf randomness and the repository's Kolmogorov–Loveland +randomness predicate define different classes. -/ +theorem kolmogorovLovelandRandom_ne_martinLofRandom : + {X : Cantor | KolmogorovLovelandRandom X} ≠ {X : Cantor | MartinLofRandom X} := by + obtain ⟨X, hKL, hML⟩ := exists_kolmogorovLovelandRandom_not_martinLofRandom + intro h + exact hML (show X ∈ {X : Cantor | MartinLofRandom X} from h ▸ hKL) + +/-- The Martin-Löf random class is a proper subset of the class defined +by total computable-real Kolmogorov–Loveland betting strategies. -/ +theorem martinLofRandom_ssubset_kolmogorovLovelandRandom : + {X : Cantor | MartinLofRandom X} ⊂ {X : Cantor | KolmogorovLovelandRandom X} := by + refine Set.ssubset_iff_subset_ne.mpr ⟨?_, ?_⟩ + · exact fun _ h => h.kolmogorovLovelandRandom + · exact Ne.symm kolmogorovLovelandRandom_ne_martinLofRandom + +end Klr diff --git a/LeanPool/KLRandomness/Sparse.lean b/LeanPool/KLRandomness/Sparse.lean new file mode 100644 index 0000000000..520244b2f4 --- /dev/null +++ b/LeanPool/KLRandomness/Sparse.lean @@ -0,0 +1,116 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import Mathlib.Algebra.Order.BigOperators.Ring.Finset +public import Mathlib.Analysis.SpecialFunctions.Sqrt +import Mathlib.Tactic.Linarith +import Mathlib.Tactic.Positivity +import Mathlib.Tactic.Push +import Mathlib.Tactic.Ring + +/-! +# Sparse supports and total wager + +The deterministic averaging estimate in Section 5 of Liu and Meng, +arXiv:2611.31004v1. If each position belongs to few candidate supports, +then the average total wager on a candidate is small. A square-sum bound +controls the total wager on the pool by Cauchy–Schwarz. + +This file proves the estimate for an already supplied finite family. +It does not construct the sparse, rank-preserving family of Lemma 4. +-/ + +@[expose] public section + +namespace Klr.Sparse + +open scoped BigOperators + +variable {α Q : Type*} [Fintype α] [Fintype Q] + +/-- How many candidate supports contain a particular position. -/ +def incidence [DecidableEq α] (S : Q → Finset α) (a : α) : ℕ := + (Finset.univ.filter (fun q => a ∈ S q)).card + +/-- Double counting, with an arbitrary real weight on each pool position. -/ +theorem sum_support_weights [DecidableEq α] (S : Q → Finset α) (w : α → ℝ) : + (∑ q, ∑ a ∈ S q, w a) = ∑ a, (incidence S a : ℝ) * w a := by + classical + calc + (∑ q, ∑ a ∈ S q, w a) = ∑ q, ∑ a, if a ∈ S q then w a else 0 := by + apply Finset.sum_congr rfl + intro q hq + rw [← Finset.sum_filter] + simp + _ = ∑ a, ∑ q, if a ∈ S q then w a else 0 := Finset.sum_comm + _ = ∑ a, (incidence S a : ℝ) * w a := by + apply Finset.sum_congr rfl + intro a ha + rw [← Finset.sum_filter] + simp [incidence] + +/-- The incidence bound controls the sum over all candidates. -/ +theorem sum_support_weights_le [DecidableEq α] (S : Q → Finset α) (w : α → ℝ) (B : ℝ) + (hw : ∀ a, 0 ≤ w a) (hS : ∀ a, (incidence S a : ℝ) ≤ B) : + (∑ q, ∑ a ∈ S q, w a) ≤ B * ∑ a, w a := by + rw [sum_support_weights, Finset.mul_sum] + exact Finset.sum_le_sum fun a _ => mul_le_mul_of_nonneg_right (hS a) (hw a) + +/-- Cauchy–Schwarz turns a square-sum budget into an ordinary sum budget. -/ +theorem sum_weights_le_sqrt (w : α → ℝ) (C : ℝ) + (hw : ∀ a, 0 ≤ w a) (hC : ∑ a, (w a) ^ 2 ≤ C) : + (∑ a, w a) ≤ Real.sqrt ((Fintype.card α : ℝ) * C) := by + have hCS := Finset.sum_mul_sq_le_sq_mul_sq + (s := (Finset.univ : Finset α)) (f := fun _ => (1 : ℝ)) (g := w) + simp only [one_mul, one_pow, Finset.sum_const, Finset.card_univ, nsmul_eq_mul, + mul_one] at hCS + have hcard : 0 ≤ (Fintype.card α : ℝ) := Nat.cast_nonneg _ + have hsq : (∑ a, w a) ^ 2 ≤ (Fintype.card α : ℝ) * C := + hCS.trans (mul_le_mul_of_nonneg_left hC hcard) + have hs : 0 ≤ ∑ a, w a := Finset.sum_nonneg fun a _ => hw a + exact (Real.le_sqrt hs ((sq_nonneg _).trans hsq)).2 hsq + +/-- Averaging over a nonempty candidate family. `δ` bounds the fraction of +candidates containing any one position. -/ +theorem average_support_weights_le [DecidableEq α] [Nonempty Q] + (S : Q → Finset α) (w : α → ℝ) (δ C : ℝ) + (hw : ∀ a, 0 ≤ w a) (hδ : 0 ≤ δ) + (hS : ∀ a, (incidence S a : ℝ) ≤ δ * Fintype.card Q) + (hC : ∑ a, (w a) ^ 2 ≤ C) : + (∑ q, ∑ a ∈ S q, w a) / Fintype.card Q ≤ + δ * Real.sqrt ((Fintype.card α : ℝ) * C) := by + have hQ : (0 : ℝ) < Fintype.card Q := by exact_mod_cast Fintype.card_pos + apply (div_le_iff₀ hQ).2 + calc + (∑ q, ∑ a ∈ S q, w a) ≤ (δ * Fintype.card Q) * ∑ a, w a := + sum_support_weights_le S w _ hw hS + _ ≤ (δ * Fintype.card Q) * Real.sqrt ((Fintype.card α : ℝ) * C) := + mul_le_mul_of_nonneg_left (sum_weights_le_sqrt w C hw hC) (by positivity) + _ = (δ * Real.sqrt ((Fintype.card α : ℝ) * C)) * Fintype.card Q := by ring + +/-- Some candidate does at least as well as the average bound. -/ +theorem exists_small_support [DecidableEq α] [Nonempty Q] + (S : Q → Finset α) (w : α → ℝ) (δ C : ℝ) + (hw : ∀ a, 0 ≤ w a) (hδ : 0 ≤ δ) + (hS : ∀ a, (incidence S a : ℝ) ≤ δ * Fintype.card Q) + (hC : ∑ a, (w a) ^ 2 ≤ C) : + ∃ q, (∑ a ∈ S q, w a) ≤ δ * Real.sqrt ((Fintype.card α : ℝ) * C) := by + classical + have havg := average_support_weights_le S w δ C hw hδ hS hC + have hQ : (0 : ℝ) < Fintype.card Q := by exact_mod_cast Fintype.card_pos + by_contra hn + push Not at hn + have hsum : (Fintype.card Q : ℝ) * (δ * Real.sqrt ((Fintype.card α : ℝ) * C)) < + ∑ q, ∑ a ∈ S q, w a := by + simpa using Finset.sum_lt_sum_of_nonempty Finset.univ_nonempty (fun q _ => hn q) + have := (div_le_iff₀ hQ).mp havg + nlinarith + +end Klr.Sparse diff --git a/LeanPool/KLRandomness/SparseCandidate.lean b/LeanPool/KLRandomness/SparseCandidate.lean new file mode 100644 index 0000000000..329ccab361 --- /dev/null +++ b/LeanPool/KLRandomness/SparseCandidate.lean @@ -0,0 +1,149 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.UniformSupport +public import LeanPool.KLRandomness.RandomMatrix +import Mathlib.Tactic.Positivity + +/-! +# The actual finite experiment for sparse affine candidates + +A candidate is a uniformly selected support of size `m`, paired independently +with a uniformly selected full-row-rank binary matrix with `m` columns. A fixed +enumeration of each support identifies unread pool positions with matrix +columns. Thus the probability bounds below are for an actual finite sample +space, with no assumed intersection moments or rank-failure estimates. +-/ + +@[expose] public section + +namespace Klr.SparseCandidate + +open FiniteProbability UniformSupport RandomMatrix +open scoped BigOperators + +variable {M m r : ℕ} + +/-- The support and full-rank matrix are sampled independently and uniformly. -/ +abbrev Candidate (M m r : ℕ) := Support M m × FullRankMatrix (Fin m) r + +/-- A fixed enumeration of the positions of a size-`m` support. -/ +noncomputable def supportEquiv (S : Support M m) : Fin m ≃ S.val := + Fintype.equivOfCardEq (by simp [S.property]) + +/-- The corresponding injection of column indices into pool positions. -/ +noncomputable def position (S : Support M m) : Fin m ↪ Fin M where + toFun j := (supportEquiv S j).val + inj' _ _ h := (supportEquiv S).injective (Subtype.ext h) + +theorem position_mem (S : Support M m) (j : Fin m) : position S j ∈ S.val := + (supportEquiv S j).property + +/-- The columns located at unread positions of the pool. -/ +noncomputable def unreadColumns (D : Finset (Fin M)) (S : Support M m) : Finset (Fin m) := + Finset.univ.filter (fun j => position S j ∈ D) + +@[simp] theorem mem_unreadColumns (D : Finset (Fin M)) (S : Support M m) (j : Fin m) : + j ∈ unreadColumns D S ↔ position S j ∈ D := by + simp [unreadColumns] + +theorem map_unreadColumns (D : Finset (Fin M)) (S : Support M m) : + (unreadColumns D S).map (position S) = S.val ∩ D := by + ext a + constructor + · intro ha + obtain ⟨j, hj, rfl⟩ := Finset.mem_map.mp ha + exact Finset.mem_inter.mpr ⟨position_mem S j, (mem_unreadColumns D S j).mp hj⟩ + · intro ha + obtain ⟨hS, hD⟩ := Finset.mem_inter.mp ha + let j := (supportEquiv S).symm ⟨a, hS⟩ + have hj : position S j = a := by + exact congrArg Subtype.val ((supportEquiv S).apply_symm_apply ⟨a, hS⟩) + exact Finset.mem_map.mpr ⟨j, (mem_unreadColumns D S j).mpr (hj ▸ hD), hj⟩ + +/-- The unread-column count is exactly the support intersection size. -/ +@[simp] theorem card_unreadColumns (D : Finset (Fin M)) (S : Support M m) : + (unreadColumns D S).card = (S.val ∩ D).card := by + rw [← map_unreadColumns D S, Finset.card_map] + +/-- Rank failure of the candidate's matrix on the unread pool positions. -/ +def BadRank (D : Finset (Fin M)) (c : Candidate M m r) : Prop := + ¬ Function.Surjective (restrictedMap c.2.val (unreadColumns D c.1) (K := ZMod 2)) + +theorem candidate_nonempty (hmM : m ≤ M) (hrm : r + 1 ≤ m) : + Nonempty (Candidate M m r) := by + have : Nonempty (Support M m) := support_nonempty hmM + have : Nonempty (FullRankMatrix (Fin m) r) := + nonempty_fullRankMatrix_of_card (by simpa using hrm) + infer_instance + +/-- Every pool position has exactly the inclusion probability `m/M`. -/ +theorem probability_contains (hm1 : 1 ≤ m) (hmM : m ≤ M) (hrm : r + 1 ≤ m) + (a : Fin M) : + probability {c : Candidate M m r | a ∈ c.1.val} = (m : ℝ) / M := by + classical + have : Nonempty (FullRankMatrix (Fin m) r) := + nonempty_fullRankMatrix_of_card (by simpa using hrm) + rw [probability_prod_fiber] + calc + _ = average (inclusion (m := m) a) := by + apply average_congr + intro S + by_cases h : a ∈ S.val <;> simp [h, inclusion] + _ = _ := average_inclusion hm1 hmM a + +/-- On supports with at least `2r` unread positions, the conditional matrix +rank-failure probability is at most `2 * 2^(-r)`. -/ +theorem probability_badRank_fiber_le (D : Finset (Fin M)) (S : Support M m) + (hrm : r + 1 ≤ m) (hS : 2 * r ≤ (S.val ∩ D).card) : + probability {B : FullRankMatrix (Fin m) r | BadRank D (S, B)} ≤ + 2 * (1 / 2 : ℝ) ^ r := by + exact full_rank_restricted_failure_probability_le_pow_of_card (unreadColumns D S) + (by simpa using hrm) (by simpa using hS) + +/-- The rank-failure probability of the actual sparse candidate experiment. +The two terms account for a support with fewer than `2r` unread positions and +for rank failure of the full-rank-conditioned matrix on the remaining supports. -/ +theorem probability_badRank_le (hm2 : 2 ≤ m) (hmM : m ≤ M) (hrm : r + 1 ≤ m) + (D : Finset (Fin M)) (τ : ℝ) (hτ : 0 < τ) + (hD : τ * M ≤ (D.card : ℝ)) (hr : 4 * (r : ℝ) ≤ τ * m) : + probability {c : Candidate M m r | BadRank D c} ≤ + 4 / (τ * m) + 2 * (1 / 2 : ℝ) ^ r := by + classical + have : Nonempty (Support M m) := support_nonempty hmM + have : Nonempty (FullRankMatrix (Fin m) r) := + nonempty_fullRankMatrix_of_card (by simpa using hrm) + have hq : 0 ≤ 2 * (1 / 2 : ℝ) ^ r := by positivity + rw [probability_prod_fiber] + calc + _ ≤ average (fun S : Support M m => + (if (S.val ∩ D).card < 2 * r then (1 : ℝ) else 0) + + 2 * (1 / 2 : ℝ) ^ r) := by + apply average_mono + intro S + change probability {B : FullRankMatrix (Fin m) r | BadRank D (S, B)} ≤ _ + by_cases hS : (S.val ∩ D).card < 2 * r + · simpa only [ite_eq_left hS] using + (probability_le_one {B : FullRankMatrix (Fin m) r | BadRank D (S, B)}).trans + (le_add_of_nonneg_right hq) + · simpa only [ite_eq_right hS, zero_add] using + probability_badRank_fiber_le D S hrm (by omega) + _ = probability {S : Support M m | (S.val ∩ D).card < 2 * r} + + 2 * (1 / 2 : ℝ) ^ r := by + rw [average_add, average_const] + congr 1 + unfold probability + apply average_congr + intro S + by_cases hS : (S.val ∩ D).card < 2 * r <;> simp [hS] + _ ≤ _ := add_le_add + (probability_small_intersection_le_density hm2 hmM D r τ hτ hD hr) le_rfl + +end Klr.SparseCandidate diff --git a/LeanPool/KLRandomness/SparseCandidateCode.lean b/LeanPool/KLRandomness/SparseCandidateCode.lean new file mode 100644 index 0000000000..8ffc16da60 --- /dev/null +++ b/LeanPool/KLRandomness/SparseCandidateCode.lean @@ -0,0 +1,136 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.SparseCandidate +public import LeanPool.KLRandomness.SparseSearchMask +public import LeanPool.KLRandomness.AffineCodeCoverage +public import LeanPool.KLRandomness.SparseCodeCount + +/-! +# Concrete matrix codes for the probabilistic candidates + +The matrix on a candidate's support is padded by zero columns to the whole +pool. Padding preserves full row rank and every unread-column rank test. +This supplies the algebraic bridge from the classical finite experiment to +the executable code representation used by exhaustive search. +-/ + +@[expose] public section + +namespace Klr.SparseCandidateCode + +open SparseCandidate RandomMatrix AffineCode FiniteMeasure + +variable {M m r : ℕ} + +/-- The candidate's columns, extended by zero to the whole pool. -/ +noncomputable def paddedColumns (c : Candidate M m r) (a : Fin M) : Fin r → ZMod 2 := + if ha : a ∈ c.1.val then c.2.val ((supportEquiv c.1).symm ⟨a, ha⟩) else 0 + +@[simp] theorem paddedColumns_position (c : Candidate M m r) (j : Fin m) : + paddedColumns c (position c.1 j) = c.2.val j := by + simp only [paddedColumns, dite_eq_left (position_mem c.1 j)] + change c.2.val ((supportEquiv c.1).symm (supportEquiv c.1 j)) = _ + rw [Equiv.symm_apply_apply] + +/-- Restricting padded columns to unread pool positions is exactly restricting +the original matrix to the corresponding support columns. -/ +theorem padded_restricted_surjective_iff (c : Candidate M m r) (D : Finset (Fin M)) : + Function.Surjective (restrictedMap (paddedColumns c) D (K := ZMod 2)) ↔ + Function.Surjective + (restrictedMap c.2.val (unreadColumns D c.1) (K := ZMod 2)) := by + classical + rw [← not_iff_not, restricted_not_surjective_iff, restricted_not_surjective_iff] + constructor + · rintro ⟨φ, hφ, hD⟩ + refine ⟨φ, hφ, funext fun j => ?_⟩ + have hj : position c.1 j.val ∈ D := (mem_unreadColumns D c.1 j.val).mp j.property + have he := congrFun hD ⟨position c.1 j.val, hj⟩ + simpa only [evaluationMap_apply, paddedColumns_position, Pi.zero_apply] using he + · rintro ⟨φ, hφ, hT⟩ + refine ⟨φ, hφ, funext fun a => ?_⟩ + change φ (paddedColumns c a.val) = 0 + by_cases hS : a.val ∈ c.1.val + · let j := (supportEquiv c.1).symm ⟨a.val, hS⟩ + have hjpos : position c.1 j = a.val := by + exact congrArg Subtype.val ((supportEquiv c.1).apply_symm_apply ⟨a.val, hS⟩) + have hj : j ∈ unreadColumns D c.1 := by + rw [mem_unreadColumns, hjpos] + exact a.property + have he := congrFun hT ⟨j, hj⟩ + simpa only [paddedColumns, dite_eq_left hS, evaluationMap_apply, Pi.zero_apply] using he + · simp [paddedColumns, hS] + +theorem padded_surjective (c : Candidate M m r) : + Function.Surjective (columnMap (paddedColumns c) (K := ZMod 2)) := by + have he : unreadColumns Finset.univ c.1 = Finset.univ := by ext j; simp + have h := padded_restricted_surjective_iff c Finset.univ + rw [he, restricted_univ_surjective_iff, restricted_univ_surjective_iff] at h + exact h.mpr c.2.property + +/-- Encode the padded candidate matrix. Sparse-list checking uses the direct +rank test, so no right-inverse certificate or syndrome is needed at this point. -/ +noncomputable def code (c : Candidate M m r) : Data := + AffineCode.encode (fun i a => paddedColumns c a i) 0 0 + +@[simp] theorem width_code (c : Candidate M m r) : width (code c) = M := rfl +@[simp] theorem rank_code (c : Candidate M m r) : rank (code c) = r := rfl + +@[simp] theorem matrix_code (c : Candidate M m r) : + matrix (code c) = fun i a => paddedColumns c a i := matrix_encode _ _ _ + +theorem surjective_code (c : Candidate M m r) : + Function.Surjective (matrix (code c)).mulVecLin := by + rw [matrix_code] + change Function.Surjective + (Matrix.mulVecLin (Matrix.of (fun (i : Fin r) (a : Fin M) => paddedColumns c a i))) + rw [SparseSearch.mulVecLin_eq_columnMap] + exact padded_surjective c + +@[simp] theorem fullRank_code (c : Candidate M m r) : SparseSearch.fullRank (code c) = true := + (SparseSearch.fullRank_eq_true _).mpr (surjective_code c) + +/-- Every coefficient outside the support is literally the Boolean value false. -/ +theorem entry_code_eq_false (c : Candidate M m r) (i j : ℕ) + (hi : i < r) (hj : j < M) (hS : (⟨j, hj⟩ : Fin M) ∉ c.1.val) : + entry (rows (code c)) i j = false := by + have hp : paddedColumns c (⟨j, hj⟩ : Fin M) = 0 := by + simp [paddedColumns, hS] + change ((List.ofFn (fun i : Fin r => List.ofFn + (fun j : Fin M => boolEquivF2.symm (paddedColumns c j i)))).getD i []).getD j false = false + rw [AffineCode.getD_ofFn _ ⟨i, hi⟩, AffineCode.getD_ofFn _ ⟨j, hj⟩, hp] + rfl + +/-- The executable mask checker on the padded code is exactly the candidate +rank-preservation predicate on the corresponding unread pool positions. -/ +theorem maskedFullRank_code (c : Candidate M m r) (d : List Bool) : + SparseSearch.maskedFullRank (code c) d = true ↔ + ¬ BadRank (SparseListCode.maskSet M d) c := by + classical + rw [SparseSearch.maskedFullRank_eq_true] + change Function.Surjective + (restrictedMap (fun (a : Fin M) (i : Fin r) => matrix (code c) i a) + (SparseListCode.maskSet M d) (K := ZMod 2)) ↔ _ + have hcols : (fun (a : Fin M) (i : Fin r) => matrix (code c) i a) = + paddedColumns c := by + funext a i + exact congrFun (congrFun (matrix_code c) i) a + rw [hcols] + simpa only [BadRank, not_not] using + padded_restricted_surjective_iff c (SparseListCode.maskSet M d) + +theorem maskedFullRank_code_false (c : Candidate M m r) (d : List Bool) : + (!SparseSearch.maskedFullRank (code c) d) = true ↔ + BadRank (SparseListCode.maskSet M d) c := by + classical + have h := maskedFullRank_code c d + cases he : SparseSearch.maskedFullRank (code c) d <;> simp_all + +end Klr.SparseCandidateCode diff --git a/LeanPool/KLRandomness/SparseCandidateList.lean b/LeanPool/KLRandomness/SparseCandidateList.lean new file mode 100644 index 0000000000..9931cc7f09 --- /dev/null +++ b/LeanPool/KLRandomness/SparseCandidateList.lean @@ -0,0 +1,132 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.SparseCandidate +public import LeanPool.KLRandomness.SampleConcentration +public import LeanPool.KLRandomness.SparseParameters +import Mathlib.Tactic.FieldSimp +import Mathlib.Tactic.GCongr +import Mathlib.Tactic.NormNum +import Mathlib.Tactic.Positivity +import Mathlib.Tactic.Ring + +/-! +# Existence of sparse rank-preserving candidate lists + +This is the finite combinatorial existence assertion in Lemma 4. All marginal +probabilities, concentration bounds, and eventual parameter inequalities are +proved for actual finite sample spaces in the imported modules. +-/ + +@[expose] public section + +namespace Klr.SparseCandidateList + +open FiniteProbability SampleConcentration SparseCandidate + +variable {M m r J : ℕ} + +/-- The two simultaneous requirements on a candidate list. Repetitions are +allowed, as in independent sampling with replacement. -/ +structure IsGood (z : Fin J → Candidate M m r) (τ θ : ℝ) : Prop where + incidence : ∀ a : Fin M, + (count {c : Candidate M m r | a ∈ c.1.val} z : ℝ) ≤ 2 * ((m : ℝ) / M) * J + preservesRank : ∀ D : Finset (Fin M), τ * M ≤ (D.card : ℝ) → + (count {c : Candidate M m r | BadRank D c} z : ℝ) ≤ θ * J + +/-- Finite parameter criterion for a sparse rank-preserving list. -/ +theorem exists_goodList (hm2 : 2 ≤ m) (hmM : m ≤ M) (hrm : r + 1 ≤ m) + (τ θ : ℝ) (hτ : 0 < τ) (hθ : 0 ≤ θ) + (hr : 4 * (r : ℝ) ≤ τ * m) + (hp : 4 / (τ * m) + 2 * (1 / 2 : ℝ) ^ r ≤ θ / 4) + (hsmall : Real.exp ((M : ℝ) - θ * J / 4) + + M * Real.exp (-(((m : ℝ) / M) * J) / 6) < 1) : + ∃ z : Fin J → Candidate M m r, IsGood z τ θ := by + classical + have : Nonempty (Candidate M m r) := candidate_nonempty hmM hrm + let A : Finset (Fin M) → Set (Candidate M m r) := + fun D => {c | τ * M ≤ (D.card : ℝ) ∧ BadRank D c} + let B : Fin M → Set (Candidate M m r) := fun a => {c | a ∈ c.1.val} + have hA : ∀ D, probability (A D) ≤ θ / 4 := by + intro D + by_cases hD : τ * M ≤ (D.card : ℝ) + · have hsub : A D ⊆ {c : Candidate M m r | BadRank D c} := fun _ hc => hc.2 + exact (probability_mono hsub).trans + ((probability_badRank_le hm2 hmM hrm D τ hτ hD hr).trans hp) + · simp only [A, hD, false_and, Set.ofPred_false, probability_empty] + positivity + have hB : ∀ a, probability (B a) ≤ (m : ℝ) / M := by + intro a + exact le_of_eq (probability_contains (by omega) hmM hrm a) + have htwo : (2 : ℝ) ^ M ≤ Real.exp M := by + calc + (2 : ℝ) ^ M ≤ (Real.exp 1) ^ M := by + apply pow_le_pow_left₀ (by norm_num) + have h := Real.add_one_le_exp (1 : ℝ) + norm_num at h + exact h + _ = Real.exp M := by rw [← Real.exp_nat_mul]; simp + have hs : Fintype.card (Finset (Fin M)) * Real.exp (-(θ * J) / 4) + + Fintype.card (Fin M) * Real.exp (-(((m : ℝ) / M) * J) / 6) < 1 := by + calc + _ = (2 : ℝ) ^ M * Real.exp (-(θ * J) / 4) + + M * Real.exp (-(((m : ℝ) / M) * J) / 6) := by simp + _ ≤ Real.exp ((M : ℝ) - θ * J / 4) + + M * Real.exp (-(((m : ℝ) / M) * J) / 6) := by + apply add_le_add _ le_rfl + calc + (2 : ℝ) ^ M * Real.exp (-(θ * J) / 4) ≤ + Real.exp M * Real.exp (-(θ * J) / 4) := by gcongr + _ = Real.exp ((M : ℝ) - θ * J / 4) := by + rw [← Real.exp_add] + congr 1 + ring + _ < 1 := hsmall + obtain ⟨z, hzA, hzB⟩ := exists_simultaneous_samples A B J θ ((m : ℝ) / M) + hθ (by positivity) hA hB hs + refine ⟨z, hzB, ?_⟩ + intro D hD + have he : A D = {c : Candidate M m r | BadRank D c} := by + ext c + simp [A, hD] + simpa only [he] using hzA D + +/-- Lemma 4's combinatorial existence assertion, with the paper's polynomial +parameters, holds for every sufficiently large rank. -/ +theorem eventually_exists_goodList (τ θ : ℝ) (hτ : 0 < τ) (hθ : 0 < θ) : + ∀ᶠ r : ℕ in Filter.atTop, + ∃ z : Fin (SparseParameters.listSize r) → + Candidate (SparseParameters.blockSize r) (SparseParameters.supportSize r) r, + IsGood z τ θ := by + filter_upwards [SparseParameters.eventually_candidate_parameters τ θ hτ hθ] + with r hr + obtain ⟨hm2, hmM, hrm, hmargin, hsingle, hlist⟩ := hr + have hM0 : (SparseParameters.blockSize r : ℝ) ≠ 0 := by + have hn : SparseParameters.blockSize r ≠ 0 := by omega + exact_mod_cast hn + have he : ((SparseParameters.supportSize r : ℝ) / SparseParameters.blockSize r) * + SparseParameters.listSize r = + (SparseParameters.supportSize r : ℝ) * (SparseParameters.blockSize r : ℝ) ^ 2 := by + simp only [SparseParameters.listSize, Nat.cast_pow] + field_simp [hM0] + apply exists_goodList hm2 hmM hrm τ θ hτ (le_of_lt hθ) hmargin hsingle + rw [he] + simpa only [neg_mul] using hlist + +/-- Candidate lists can be obtained above any previously imposed lower bound +on the rank. This is the form needed for iterative stage choices. -/ +theorem exists_goodList_above (τ θ : ℝ) (hτ : 0 < τ) (hθ : 0 < θ) (R : ℕ) : + ∃ r ≥ R, ∃ z : Fin (SparseParameters.listSize r) → + Candidate (SparseParameters.blockSize r) (SparseParameters.supportSize r) r, + IsGood z τ θ := by + obtain ⟨N, hN⟩ := Filter.eventually_atTop.mp (eventually_exists_goodList τ θ hτ hθ) + exact ⟨max R N, le_max_left _ _, hN _ (le_max_right _ _)⟩ + +end Klr.SparseCandidateList diff --git a/LeanPool/KLRandomness/SparseCandidateWeights.lean b/LeanPool/KLRandomness/SparseCandidateWeights.lean new file mode 100644 index 0000000000..54eea858bd --- /dev/null +++ b/LeanPool/KLRandomness/SparseCandidateWeights.lean @@ -0,0 +1,147 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.SparseCandidate +public import LeanPool.KLRandomness.SparseCandidateList +public import LeanPool.KLRandomness.SampleConcentration +public import LeanPool.KLRandomness.Sparse +import Mathlib.Tactic.Linarith +import Mathlib.Tactic.Positivity + +/-! +# Small support weight among rank-preserving candidates + +The incidence conclusion of the finite sampling construction is exactly the +hypothesis of the deterministic sparse-support estimate. If at most a `θ` +fraction of a nonempty list loses rank, restricting to the rank-preserving +indices costs only the factor `1 / (1 - θ)` in the support-weight bound. +-/ + +@[expose] public section + +namespace Klr.SparseCandidateWeights + +open SparseCandidate SampleConcentration +open scoped BigOperators + +variable {M m r J : ℕ} + +/-- The total nonnegative weight on a candidate's support. -/ +def supportWeight (w : Fin M → ℝ) (c : Candidate M m r) : ℝ := + ∑ a ∈ c.1.val, w a + +theorem supportWeight_nonneg (w : Fin M → ℝ) (hw : ∀ a, 0 ≤ w a) + (c : Candidate M m r) : 0 ≤ supportWeight w c := + Finset.sum_nonneg fun a _ => hw a + +/-- The sample count and the sparse-support incidence API count the same indices. -/ +theorem incidence_eq_count (z : Fin J → Candidate M m r) (a : Fin M) : + Sparse.incidence (fun j => (z j).1.val) a = count {c | a ∈ c.1.val} z := by + classical + unfold Sparse.incidence count + congr 1 + ext j + simp + +/-- The selected list satisfies the deterministic average-weight estimate. -/ +theorem average_supportWeight_le (z : Fin J → Candidate M m r) (hJ : 0 < J) + (hinc : ∀ a, (count {c | a ∈ c.1.val} z : ℝ) ≤ 2 * ((m : ℝ) / M) * J) + (w : Fin M → ℝ) (C : ℝ) (hw : ∀ a, 0 ≤ w a) + (hC : ∑ a, (w a) ^ 2 ≤ C) : + (∑ j, supportWeight w (z j)) / J ≤ + (2 * ((m : ℝ) / M)) * Real.sqrt ((M : ℝ) * C) := by + have : Nonempty (Fin J) := ⟨⟨0, hJ⟩⟩ + have hi : ∀ a, (Sparse.incidence (fun j => (z j).1.val) a : ℝ) ≤ + (2 * ((m : ℝ) / M)) * Fintype.card (Fin J) := by + intro a + simpa only [incidence_eq_count, Fintype.card_fin] using hinc a + simpa only [supportWeight, Fintype.card_fin] using + Sparse.average_support_weights_le (fun j => (z j).1.val) w + (2 * ((m : ℝ) / M)) C hw (by positivity) hi hC + +/-- Restricting a support family to a subtype cannot increase any incidence. -/ +theorem incidence_subtype_le {Q : Type*} [Fintype Q] (S : Q → Finset (Fin M)) + (P : Q → Prop) [Fintype {q // P q}] (a : Fin M) : + Sparse.incidence (fun q : {q // P q} => S q.val) a ≤ Sparse.incidence S a := by + classical + unfold Sparse.incidence + apply Finset.card_le_card_of_injOn (fun q : {q // P q} => q.val) + · intro q hq + simpa using hq + · intro q _ q' _ h + exact Subtype.ext h + +/-- A rank-preserving candidate of small support weight exists in every list +whose incidence and bad-rank counts satisfy the sampling bounds. -/ +theorem exists_rank_good_small_weight (z : Fin J → Candidate M m r) (hJ : 0 < J) + (hinc : ∀ a, (count {c | a ∈ c.1.val} z : ℝ) ≤ 2 * ((m : ℝ) / M) * J) + (D : Finset (Fin M)) (θ : ℝ) (hθ : θ < 1) + (hrank : (count {c | BadRank D c} z : ℝ) ≤ θ * J) + (w : Fin M → ℝ) (C : ℝ) (hw : ∀ a, 0 ≤ w a) + (hC : ∑ a, (w a) ^ 2 ≤ C) : + ∃ j, ¬ BadRank D (z j) ∧ supportWeight w (z j) ≤ + ((2 * ((m : ℝ) / M)) / (1 - θ)) * Real.sqrt ((M : ℝ) * C) := by + classical + let G := {j : Fin J // ¬ BadRank D (z j)} + have hpartition : count {c | BadRank D c} z + Fintype.card G = J := by + simpa only [count, G, Fintype.card_subtype, Finset.card_univ, + Fintype.card_fin, Set.mem_ofPred_eq] using + (Finset.card_filter_add_card_filter_not (s := (Finset.univ : Finset (Fin J))) + (fun j => BadRank D (z j))) + have hpartition' : (count {c | BadRank D c} z : ℝ) + Fintype.card G = J := by + exact_mod_cast hpartition + have hgood : (1 - θ) * J ≤ (Fintype.card G : ℝ) := by linarith + have hθpos : 0 < 1 - θ := sub_pos.mpr hθ + have hJpos : (0 : ℝ) < J := by exact_mod_cast hJ + have hGpos : 0 < Fintype.card G := by + have h := (mul_pos hθpos hJpos).trans_le hgood + exact_mod_cast h + have : Nonempty G := Fintype.card_pos_iff.mp hGpos + have hδ : 0 ≤ 2 * ((m : ℝ) / M) := by positivity + have hi : ∀ a, (Sparse.incidence (fun j : G => (z j.val).1.val) a : ℝ) ≤ + ((2 * ((m : ℝ) / M)) / (1 - θ)) * Fintype.card G := by + intro a + have hi0 : (Sparse.incidence (fun j : G => (z j.val).1.val) a : ℝ) ≤ + (Sparse.incidence (fun j => (z j).1.val) a : ℝ) := by + exact_mod_cast incidence_subtype_le (fun j => (z j).1.val) + (fun j => ¬ BadRank D (z j)) a + calc + _ ≤ 2 * ((m : ℝ) / M) * J := by + exact hi0.trans (by simpa only [incidence_eq_count] using hinc a) + _ ≤ _ := by + rw [div_mul_eq_mul_div] + apply (le_div_iff₀ hθpos).mpr + nlinarith [mul_le_mul_of_nonneg_left hgood hδ] + obtain ⟨j, hj⟩ := Sparse.exists_small_support (fun j : G => (z j.val).1.val) w + ((2 * ((m : ℝ) / M)) / (1 - θ)) C hw (div_nonneg hδ hθpos.le) hi hC + exact ⟨j.val, j.property, by simpa only [supportWeight, Fintype.card_fin] using hj⟩ + +/-- The average-weight bound applied directly to a list from Lemma 4. -/ +theorem average_supportWeight_le_of_isGood (z : Fin J → Candidate M m r) + {τ θ : ℝ} (hz : SparseCandidateList.IsGood z τ θ) (hJ : 0 < J) + (w : Fin M → ℝ) (C : ℝ) (hw : ∀ a, 0 ≤ w a) + (hC : ∑ a, (w a) ^ 2 ≤ C) : + (∑ j, supportWeight w (z j)) / J ≤ + (2 * ((m : ℝ) / M)) * Real.sqrt ((M : ℝ) * C) := + average_supportWeight_le z hJ hz.incidence w C hw hC + +/-- A dense unread set and a sparse rank-preserving list give a candidate +that both preserves rank and has the asserted small total support weight. -/ +theorem exists_rank_good_small_weight_of_isGood (z : Fin J → Candidate M m r) + {τ θ : ℝ} (hz : SparseCandidateList.IsGood z τ θ) (hJ : 0 < J) (hθ : θ < 1) + (D : Finset (Fin M)) (hD : τ * M ≤ (D.card : ℝ)) + (w : Fin M → ℝ) (C : ℝ) (hw : ∀ a, 0 ≤ w a) + (hC : ∑ a, (w a) ^ 2 ≤ C) : + ∃ j, ¬ BadRank D (z j) ∧ supportWeight w (z j) ≤ + ((2 * ((m : ℝ) / M)) / (1 - θ)) * Real.sqrt ((M : ℝ) * C) := + exists_rank_good_small_weight z hJ hz.incidence D θ hθ (hz.preservesRank D hD) + w C hw hC + +end Klr.SparseCandidateWeights diff --git a/LeanPool/KLRandomness/SparseCodeCount.lean b/LeanPool/KLRandomness/SparseCodeCount.lean new file mode 100644 index 0000000000..05def156a6 --- /dev/null +++ b/LeanPool/KLRandomness/SparseCodeCount.lean @@ -0,0 +1,93 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.SampleConcentration +public import Mathlib.Data.Fintype.Fin +public import Mathlib.Data.List.GetD +public import Mathlib.Data.List.OfFn + +/-! +# Boolean support masks and finite list counts + +These exact identities connect Boolean list encodings used by the computable +sparse-list verifier to finite supports and the counts in the sampling theorem. +-/ + +@[expose] public section + +namespace Klr.SparseListCode + +variable {M J : ℕ} + +/-- Count a Boolean predicate in a list generated from a finite index type. -/ +theorem countP_ofFn {α : Type*} (f : Fin J → α) (p : α → Bool) : + (List.ofFn f).countP p = + (Finset.univ.filter (fun j => p (f j) = true)).card := + List.countP_ofFn f p + +/-- The width-`M` Boolean membership mask of a finite pool subset. -/ +def mask (D : Finset (Fin M)) : List Bool := List.ofFn (fun a => decide (a ∈ D)) + +@[simp] theorem length_mask (D : Finset (Fin M)) : (mask D).length = M := by + simp [mask] + +theorem getD_mask (D : Finset (Fin M)) (a : Fin M) : + (mask D).getD a.val false = decide (a ∈ D) := by + rw [List.getD_eq_getElem _ _ (by simp)] + simp [mask] + +/-- Counting true bits in the support mask recovers the exact support size. -/ +@[simp] theorem countP_mask (D : Finset (Fin M)) : (mask D).countP id = D.card := by + simp [mask] + +/-- Decode the first `M` bits of a mask, with missing entries treated as false. -/ +def maskSet (M : ℕ) (d : List Bool) : Finset (Fin M) := + Finset.univ.filter (fun a => d.getD a.val false = true) + +@[simp] theorem mem_maskSet (M : ℕ) (d : List Bool) (a : Fin M) : + a ∈ maskSet M d ↔ d.getD a.val false = true := by + simp [maskSet] + +/-- Encoding and then decoding a support is exact. -/ +@[simp] theorem maskSet_mask (D : Finset (Fin M)) : maskSet M (mask D) = D := by + ext a + rw [mem_maskSet, getD_mask, decide_eq_true_eq] + +/-- Decoding and then encoding a mask of the prescribed width is exact. -/ +theorem mask_maskSet (M : ℕ) (d : List Bool) (hd : d.length = M) : + mask (maskSet M d) = d := by + apply List.ext_getElem (by simpa using hd.symm) + intro i hi hi' + have hiM : i < M := by simpa using hi + have h := getD_mask (maskSet M d) (⟨i, hiM⟩ : Fin M) + simpa only [List.getD_eq_getElem _ _ hi, List.getD_eq_getElem _ _ hi', + mem_maskSet, Bool.decide_eq_true] using h + +/-- Decoding a mask of length `M` preserves its count of true bits. -/ +theorem card_maskSet (M : ℕ) (d : List Bool) (hd : d.length = M) : + (maskSet M d).card = d.countP id := by + have h := countP_mask (maskSet M d) + rw [mask_maskSet M d hd] at h + exact h.symm + +/-- The verifier's Boolean list count equals the actual sample count whenever +the Boolean predicate correctly recognizes the candidate event. -/ +theorem countP_ofFn_eq_sampleCount {Ω α : Type*} (z : Fin J → Ω) + (f : Ω → α) (p : α → Bool) (A : Set Ω) + (h : ∀ c, p (f c) = true ↔ c ∈ A) : + (List.ofFn (fun j => f (z j))).countP p = SampleConcentration.count A z := by + classical + rw [countP_ofFn] + unfold SampleConcentration.count + congr 1 + ext j + simp [h] + +end Klr.SparseListCode diff --git a/LeanPool/KLRandomness/SparseListCodeBridge.lean b/LeanPool/KLRandomness/SparseListCodeBridge.lean new file mode 100644 index 0000000000..a909e0635f --- /dev/null +++ b/LeanPool/KLRandomness/SparseListCodeBridge.lean @@ -0,0 +1,114 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.SparseCandidateCode +public import LeanPool.KLRandomness.SparseCandidateList +public import LeanPool.KLRandomness.SparseListSearch +import Mathlib.Tactic.FieldSimp + +/-! +# Coding the sparse lists furnished by the probabilistic argument + +Every mathematical candidate has a concrete support mask and a zero-padded +matrix code. Exact counting and rank identities transfer both simultaneous +list conditions to the finite verifier's specification. This bridge is used +only to prove that exhaustive search has a successful code to find. +-/ + +@[expose] public section + +namespace Klr.SparseListCode + +open SparseCandidate SparseCandidateCode SampleConcentration + +variable {M m r J : ℕ} + +/-- The concrete finite representation of a mathematical candidate. -/ +noncomputable def entryOf (c : Candidate M m r) : SparseListSearch.Entry := + (mask c.1.val, SparseCandidateCode.code c) + +/-- Encode a finite list, retaining all repetitions and its index order. -/ +noncomputable def listOf (z : Fin J → Candidate M m r) : SparseListSearch.CodeList := + List.ofFn fun j => entryOf (z j) + +@[simp] theorem length_listOf (z : Fin J → Candidate M m r) : (listOf z).length = J := by + simp [listOf] + +theorem goodEntry_entryOf (c : Candidate M m r) : + SparseListSearch.GoodEntry M m r (entryOf c) := by + change (mask c.1.val).length = M ∧ (mask c.1.val).countP id = m ∧ + AffineCode.width (code c) = M ∧ AffineCode.rank (code c) = r ∧ + Function.Surjective (AffineCode.matrix (code c)).mulVecLin ∧ _ + refine ⟨length_mask _, ?_, rfl, rfl, surjective_code c, ?_⟩ + · simpa only [countP_mask] using c.1.property + · intro i hi j hj hs + apply entry_code_eq_false c i j hi hj + change (mask c.1.val).getD (⟨j, hj⟩ : Fin M).val false = false at hs + rw [getD_mask] at hs + simpa using hs + +theorem count_incidence (z : Fin J → Candidate M m r) (a : Fin M) : + (listOf z).countP (fun e => e.1.getD a.val false) = + count {c : Candidate M m r | a ∈ c.1.val} z := by + apply countP_ofFn_eq_sampleCount z entryOf + intro c + change (mask c.1.val).getD a.val false = true ↔ a ∈ c.1.val + rw [getD_mask, decide_eq_true_eq] + +theorem count_badRank (z : Fin J → Candidate M m r) (d : List Bool) : + (listOf z).countP (fun e => !SparseSearch.maskedFullRank e.2 d) = + count {c : Candidate M m r | BadRank (maskSet M d) c} z := by + apply countP_ofFn_eq_sampleCount z entryOf + intro c + exact maskedFullRank_code_false c d + +/-- A successful mathematical list yields a successful finite code. +The use of classical support enumerations here is an existence argument, +not an assertion that the encoding map is computable. -/ +theorem good_of_isGood (z : Fin J → Candidate M m r) (τ θ : ℚ) + (hz : SparseCandidateList.IsGood z (τ : ℝ) (θ : ℝ)) (hM : 0 < M) : + SparseListSearch.Good M m r J τ θ (listOf z) := by + classical + refine ⟨length_listOf z, ?_, ?_, ?_⟩ + · intro a ha + obtain ⟨j, rfl⟩ := List.mem_ofFn.mp ha + exact goodEntry_entryOf (z j) + · intro i hi + rw [count_incidence z (⟨i, hi⟩ : Fin M)] + have hinc := hz.incidence (⟨i, hi⟩ : Fin M) + have hM0 : (M : ℝ) ≠ 0 := by exact_mod_cast (ne_of_gt hM) + have he : (M : ℝ) * (2 * ((m : ℝ) / M) * J) = 2 * (m : ℝ) * J := by + field_simp [hM0] + have hm := mul_le_mul_of_nonneg_left hinc (Nat.cast_nonneg M : (0 : ℝ) ≤ M) + rw [he] at hm + exact_mod_cast hm + · intro d hd hD + rw [count_badRank] + have hdR : (τ : ℝ) * M ≤ ((maskSet M d).card : ℝ) := by + rw [card_maskSet M d hd] + exact_mod_cast hD + have hrank := hz.preservesRank (maskSet M d) hdR + exact_mod_cast hrank + +/-- The finite good-code predicate has a witness for every sufficiently large +rank and every fixed positive pair of rational parameters. -/ +theorem eventually_exists_goodCode (τ θ : ℚ) (hτ : 0 < τ) (hθ : 0 < θ) : + ∀ᶠ r : ℕ in Filter.atTop, ∃ L : SparseListSearch.CodeList, + SparseListSearch.Good (SparseParameters.blockSize r) (SparseParameters.supportSize r) + r (SparseParameters.listSize r) τ θ L := by + have hτR : (0 : ℝ) < τ := by exact_mod_cast hτ + have hθR : (0 : ℝ) < θ := by exact_mod_cast hθ + filter_upwards [SparseCandidateList.eventually_exists_goodList (τ : ℝ) (θ : ℝ) hτR hθR, + Filter.eventually_ge_atTop 1] with r hr hr1 + obtain ⟨z, hz⟩ := hr + have hM : 0 < SparseParameters.blockSize r := Nat.pow_pos (by omega) + exact ⟨listOf z, good_of_isGood z τ θ hz hM⟩ + +end Klr.SparseListCode diff --git a/LeanPool/KLRandomness/SparseListConstruction.lean b/LeanPool/KLRandomness/SparseListConstruction.lean new file mode 100644 index 0000000000..0ea692adfb --- /dev/null +++ b/LeanPool/KLRandomness/SparseListConstruction.lean @@ -0,0 +1,86 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.SparseListCodeBridge +public import LeanPool.KLRandomness.SparseListSearchEffective + +/-! +# Effective sparse rank-preserving lists + +The actual partial-recursive exhaustive search, specialized to the polynomial +parameters of Lemma 4, halts for every sufficiently large rank. Every returned +finite list meets the sparse incidence and simultaneous rank-preservation +requirements. Both effectiveness and eventual termination are proved. +-/ + +@[expose] public section + +namespace Klr.SparseListConstruction + +open SparseListSearch + +/-- The paper's parameter choice, with the rational thresholds fixed. -/ +def parameters (τ θ : ℚ) (r : ℕ) : Parameters := + (SparseParameters.blockSize r, SparseParameters.supportSize r, r, + SparseParameters.listSize r, τ, θ) + +theorem computable_pow_const (k : ℕ) : Computable (fun r : ℕ => r ^ k) := by + induction k with + | zero => simpa using (Computable.const (1 : ℕ) : Computable (fun _ : ℕ => 1)) + | succ k ih => + have h := Primrec.nat_mul.to_comp.comp ih Computable.id + exact h.of_eq fun r => (pow_succ r k).symm + +theorem computable_parameters (τ θ : ℚ) : Computable (parameters τ θ) := by + have hM := computable_pow_const 8 + have hm := computable_pow_const 2 + have hJ := (computable_pow_const 3).comp hM + have hc := hM.pair (hm.pair (Computable.id.pair + (hJ.pair ((Computable.const τ).pair (Computable.const θ))))) + exact hc.of_eq fun _ => rfl + +/-- The effective candidate-list construction. Smaller ranks may diverge. -/ +def construct (τ θ : ℚ) (r : ℕ) : Part CodeList := search (parameters τ θ r) + +theorem partrec_construct (τ θ : ℚ) : Partrec (construct τ θ) := + partrec_search.comp (computable_parameters τ θ) + +/-- Every output has the prescribed size, support cardinalities, full-rank +matrices, sparse incidences, and rank preservation for every dense unread set. -/ +theorem construct_spec {τ θ : ℚ} {r : ℕ} {L : CodeList} (hL : L ∈ construct τ θ r) : + Good (SparseParameters.blockSize r) (SparseParameters.supportSize r) + r (SparseParameters.listSize r) τ θ L := search_spec hL + +/-- The effective part of Lemma 4: for fixed positive rational parameters, +the actual list-producing computation halts at every sufficiently large rank. -/ +theorem eventually_construct_halts (τ θ : ℚ) (hτ : 0 < τ) (hθ : 0 < θ) : + ∀ᶠ r : ℕ in Filter.atTop, (construct τ θ r).Dom := by + filter_upwards [SparseListCode.eventually_exists_goodCode τ θ hτ hθ] with r hr + exact (search_dom_iff (parameters τ θ r)).mpr hr + +/-- Eventual termination together with the complete specification of the returned list. -/ +theorem eventually_construct_good (τ θ : ℚ) (hτ : 0 < τ) (hθ : 0 < θ) : + ∀ᶠ r : ℕ in Filter.atTop, ∃ L : CodeList, L ∈ construct τ θ r ∧ + Good (SparseParameters.blockSize r) (SparseParameters.supportSize r) + r (SparseParameters.listSize r) τ θ L := by + filter_upwards [eventually_construct_halts τ θ hτ hθ] with r hr + obtain ⟨L, hL⟩ := Part.dom_iff_mem.mp hr + exact ⟨L, hL, construct_spec hL⟩ + +/-- One actual Mathlib program implements the construction at the fixed +rational thresholds. No bound on its fixed header size is needed here. -/ +theorem exists_construct_program (τ θ : ℚ) : ∃ e : Nat.Partrec.Code, ∀ r : ℕ, + e.eval r = (construct τ θ r).map Encodable.encode := by + obtain ⟨e, he⟩ := Nat.Partrec.Code.exists_code.mp (partrec_construct τ θ) + refine ⟨e, fun r => ?_⟩ + rw [he] + simp only [Encodable.decode_nat, Part.coe_some, Part.bind_some] + +end Klr.SparseListConstruction diff --git a/LeanPool/KLRandomness/SparseListSearch.lean b/LeanPool/KLRandomness/SparseListSearch.lean new file mode 100644 index 0000000000..2a42a809b7 --- /dev/null +++ b/LeanPool/KLRandomness/SparseListSearch.lean @@ -0,0 +1,161 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.SparseSearchMask +public import LeanPool.KLRandomness.ComputableRational +public import LeanPool.KLRandomness.SparseCodeCount + +/-! +# A finite checker for coded sparse candidate lists + +An entry consists of a Boolean support mask and an ordinary affine-matrix +code. The matrix has ambient width `M`, with zero columns off its support. +Certificates and syndromes are irrelevant to this candidate-list check. +The rank tests use the certificate-free exhaustive checker. + +All multiplicities are list multiplicities: repeated candidates count as +separate entries. Both density thresholds are rational numbers. +-/ + +@[expose] public section + +namespace Klr.SparseListSearch + +open AffineCode SparseSearch + +/-- A support mask paired with a coded binary affine system. -/ +abbrev Entry := List Bool × AffineCode.Data +/-- A finite list of candidate supports and affine codes. -/ +abbrev CodeList := List Entry +/-- Dimensions, list length and rational thresholds of the finite candidate search. -/ +abbrev Parameters := ℕ × ℕ × ℕ × ℕ × ℚ × ℚ + +/-- Number of available positions. -/ +def universeSize (p : Parameters) : ℕ := p.1 +/-- Required number of selected positions in each support mask. -/ +def supportSize (p : Parameters) : ℕ := p.2.1 +/-- Required rank of the affine matrix in each entry. -/ +def rowRank (p : Parameters) : ℕ := p.2.2.1 +/-- Required number of candidate entries. -/ +def listLength (p : Parameters) : ℕ := p.2.2.2.1 +/-- Minimum density of the coordinate restrictions tested for rank. -/ +def density (p : Parameters) : ℚ := p.2.2.2.2.1 +/-- Maximum allowed fraction of entries losing rank on a tested restriction. -/ +def badFraction (p : Parameters) : ℚ := p.2.2.2.2.2 + +/-- Mathematical specification of one supported, full-row-rank candidate. -/ +def GoodEntry (M m r : ℕ) (a : Entry) : Prop := + a.1.length = M ∧ a.1.countP id = m ∧ width a.2 = M ∧ rank a.2 = r ∧ + Function.Surjective (matrix a.2).mulVecLin ∧ + ∀ i < r, ∀ j < M, a.1.getD j false = false → entry (rows a.2) i j = false + +/-- Deleting the zero padding preserves the candidate's full row rank. -/ +theorem GoodEntry.maskedFullRank {M m r : ℕ} {a : Entry} (h : GoodEntry M m r a) : + SparseSearch.maskedFullRank a.2 a.1 = true := by + obtain ⟨_, _, hw, hr, hf, hz⟩ := h + have hmatrix : matrix (maskCode a.2 a.1) = matrix a.2 := by + rw [matrix_maskCode] + ext i j + cases hb : a.1.getD j.val false with + | true => simp + | false => + have hi : i.val < r := by simpa only [hr] using i.isLt + have hj : j.val < M := by simpa only [hw] using j.isLt + simp [matrix, hz i.val hi j.val hj hb] + rw [SparseSearch.maskedFullRank, fullRank_eq_true, hmatrix] + exact hf + +/-- The retained support has exactly the prescribed number of columns. -/ +theorem GoodEntry.selectedColumns_card {M m r : ℕ} {a : Entry} (h : GoodEntry M m r a) : + (selectedColumns a.2 a.1).card = m := by + obtain ⟨hl, hm, hw, _⟩ := h + change (SparseListCode.maskSet (width a.2) a.1).card = m + rw [SparseListCode.card_maskSet _ _ (hl.trans hw.symm), hm] + +/-- Each accepted padded code gives a genuine full-rank system on its `m` selected columns. -/ +theorem GoodEntry.restricted_fullRank {M m r : ℕ} {a : Entry} (h : GoodEntry M m r a) : + Function.Surjective (RandomMatrix.restrictedMap + (fun j i => matrix a.2 i j) (selectedColumns a.2 a.1) (K := ZMod 2)) := + (SparseSearch.maskedFullRank_eq_true a.2 a.1).mp h.maskedFullRank + +/-- The finite sparse-list contract, using exact rational comparisons. +`maskedFullRank_eq_true` identifies the final count with failures of the +actual restricted linear map. -/ +def Good (M m r J : ℕ) (τ θ : ℚ) (L : CodeList) : Prop := + L.length = J ∧ (∀ a ∈ L, GoodEntry M m r a) ∧ + (∀ i < M, M * L.countP (fun a => a.1.getD i false) ≤ 2 * m * J) ∧ + ∀ d : List Bool, d.length = M → τ * (M : ℚ) ≤ (d.countP id : ℚ) → + (L.countP (fun a => !maskedFullRank a.2 d) : ℚ) ≤ θ * (J : ℚ) + +/-- Check that every column outside the support mask is zero. -/ +def offSupportCheck (p : Parameters) (a : Entry) : Bool := + EffectiveScan.boundedAll (fun i => EffectiveScan.boundedAll + (fun j => a.1.getD j false || !entry (rows a.2) i j) (universeSize p)) (rowRank p) + +theorem offSupportCheck_eq_true (p : Parameters) (a : Entry) : + offSupportCheck p a = true ↔ ∀ i < rowRank p, ∀ j < universeSize p, + a.1.getD j false = false → entry (rows a.2) i j = false := by + have hb (b v : Bool) : (b || !v) = true ↔ (b = false → v = false) := by + cases b <;> cases v <;> simp + simp only [offSupportCheck, EffectiveScan.boundedAll_eq_true, hb] + +/-- Check the dimensions, support and full-rank certificate of a candidate entry. -/ +def entryCheck (p : Parameters) (a : Entry) : Bool := + decide (a.1.length = universeSize p) && + (decide (a.1.countP id = supportSize p) && + (decide (width a.2 = universeSize p) && + (decide (rank a.2 = rowRank p) && (fullRank a.2 && offSupportCheck p a)))) + +theorem entryCheck_eq_true (p : Parameters) (a : Entry) : + entryCheck p a = true ↔ GoodEntry (universeSize p) (supportSize p) (rowRank p) a := by + simp only [entryCheck, Bool.and_eq_true, decide_eq_true_eq, fullRank_eq_true, + offSupportCheck_eq_true, GoodEntry] + +/-- Check the bound on how many candidates use each position. -/ +def incidenceCheck (p : Parameters) (L : CodeList) : Bool := + EffectiveScan.boundedAll (fun i => decide + (universeSize p * L.countP (fun a => a.1.getD i false) ≤ + 2 * supportSize p * listLength p)) (universeSize p) + +theorem incidenceCheck_eq_true (p : Parameters) (L : CodeList) : + incidenceCheck p L = true ↔ ∀ i < universeSize p, + universeSize p * L.countP (fun a => a.1.getD i false) ≤ + 2 * supportSize p * listLength p := by + simp only [incidenceCheck, EffectiveScan.boundedAll_eq_true, decide_eq_true_eq] + +/-- Check the rank-loss bound when the coordinate mask meets the density threshold. -/ +def restrictionCheck (p : Parameters) (L : CodeList) (d : List Bool) : Bool := + !decide (density p * (universeSize p : ℚ) ≤ (d.countP id : ℚ)) || + decide ((L.countP (fun a => !maskedFullRank a.2 d) : ℚ) ≤ + badFraction p * (listLength p : ℚ)) + +theorem restrictionCheck_eq_true (p : Parameters) (L : CodeList) (d : List Bool) : + restrictionCheck p L d = true ↔ + density p * (universeSize p : ℚ) ≤ (d.countP id : ℚ) → + (L.countP (fun a => !maskedFullRank a.2 d) : ℚ) ≤ + badFraction p * (listLength p : ℚ) := by + by_cases h : density p * (universeSize p : ℚ) ≤ (d.countP id : ℚ) + · simp [restrictionCheck, h] + · simp [restrictionCheck, h] + +/-- The complete finite verifier for an ordinary finite candidate-list code. -/ +def check (p : Parameters) (L : CodeList) : Bool := + decide (L.length = listLength p) && + (L.all (entryCheck p) && (incidenceCheck p L && + (words (universeSize p)).all (restrictionCheck p L))) + +theorem check_eq_true (p : Parameters) (L : CodeList) : + check p L = true ↔ + Good (universeSize p) (supportSize p) (rowRank p) (listLength p) + (density p) (badFraction p) L := by + simp only [check, Bool.and_eq_true, decide_eq_true_eq, List.all_eq_true, + entryCheck_eq_true, incidenceCheck_eq_true, restrictionCheck_eq_true, mem_words_iff, Good] + +end Klr.SparseListSearch diff --git a/LeanPool/KLRandomness/SparseListSearchComputable.lean b/LeanPool/KLRandomness/SparseListSearchComputable.lean new file mode 100644 index 0000000000..a15a49a531 --- /dev/null +++ b/LeanPool/KLRandomness/SparseListSearchComputable.lean @@ -0,0 +1,222 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.SparseListSearch + +/-! +# Computability of the sparse-list verifier + +Every loop in the finite checker has an explicit total computability proof. +List multiplicities are computed by a bounded counter. Rational comparisons +use the canonical rational arithmetic already implemented in the project. +-/ + +@[expose] public section + +namespace Klr.SparseListSearch + +open AffineCode SparseSearch RationalComputability + +/-- Count the true values of a Boolean predicate on an initial segment of the naturals. -/ +def boundedCount (p : ℕ → Bool) : ℕ → ℕ + | 0 => 0 + | n + 1 => boundedCount p n + if p n then 1 else 0 + +theorem boundedCount_succ_shift (p : ℕ → Bool) (n : ℕ) : + boundedCount p (n + 1) = (if p 0 then 1 else 0) + + boundedCount (fun i => p (i + 1)) n := by + induction n with + | zero => simp [boundedCount] + | succ n ih => + rw [boundedCount, ih, boundedCount, Nat.add_assoc] + +theorem boundedCount_getD {β : Type*} (p : β → Bool) (l : List β) (d : β) : + boundedCount (fun i => p (l.getD i d)) l.length = l.countP p := by + induction l with + | nil => rfl + | cons b l ih => + rw [List.length_cons, boundedCount_succ_shift, List.countP_cons] + simp only [List.getD_cons_zero, List.getD_cons_succ] + rw [ih, Nat.add_comm] + +theorem computable_boundedCount {α : Type*} [Primcodable α] {p : α → ℕ → Bool} + (hp : Computable₂ p) : Computable (fun a : α × ℕ => boundedCount (p a.1) a.2) := by + have ha : Computable (fun a : (α × ℕ) × (ℕ × ℕ) => a.1.1) := + Computable.fst.comp Computable.fst + have hi : Computable (fun a : (α × ℕ) × (ℕ × ℕ) => a.2.1) := + Computable.fst.comp Computable.snd + have hn : Computable (fun a : (α × ℕ) × (ℕ × ℕ) => a.2.2) := + Computable.snd.comp Computable.snd + have hbit := (hp.comp ha hi).cond (Computable.const 1) (Computable.const 0) + have hs := Primrec.nat_add.to_comp.comp hn hbit + apply (Computable.nat_rec Computable.snd (Computable.const 0) hs.to₂).of_eq + intro a + induction a.2 with + | zero => rfl + | succ n ih => + simpa only [boundedCount, Nat.rec_add_one, Bool.cond_eq_ite] using + congrArg (fun k => k + if p a.1 n then 1 else 0) ih + +/-- Counting a computable Boolean predicate along a computable finite list is computable. -/ +theorem computable_list_countP {α β : Type*} [Primcodable α] [Primcodable β] + [Inhabited β] {f : α → List β} {p : α → β → Bool} + (hf : Computable f) (hp : Computable₂ p) : + Computable (fun a => (f a).countP (p a)) := by + have hg : Computable (fun a : α × ℕ => (f a.1).getD a.2 default) := + (Primrec.list_getD default).to_comp.comp (hf.comp Computable.fst) Computable.snd + have hc := (computable_boundedCount + (p := fun a i => p a ((f a).getD i default)) (hp.comp Computable.fst hg)).comp + (Computable.id.pair (Computable.list_length.comp hf)) + exact hc.of_eq fun a => boundedCount_getD (p a) (f a) default + +theorem computable_countTrue : Computable (fun s : List Bool => s.countP id) := + computable_list_countP (p := fun _ b => b) Computable.id Computable.snd + +theorem computable_universeSize : Computable universeSize := Computable.fst +theorem computable_supportSize : Computable supportSize := Computable.fst.comp Computable.snd +theorem computable_rowRank : Computable rowRank := + Computable.fst.comp (Computable.snd.comp Computable.snd) +theorem computable_listLength : Computable listLength := + Computable.fst.comp (Computable.snd.comp (Computable.snd.comp Computable.snd)) +theorem computable_density : Computable density := + Computable.fst.comp + (Computable.snd.comp (Computable.snd.comp (Computable.snd.comp Computable.snd))) +theorem computable_badFraction : Computable badFraction := + Computable.snd.comp + (Computable.snd.comp (Computable.snd.comp (Computable.snd.comp Computable.snd))) + +theorem computable_offSupportCheck : Computable₂ offSupportCheck := by + have ha : Computable (fun p : ((Parameters × Entry) × ℕ) × ℕ => p.1.1.2) := + Computable.snd.comp (Computable.fst.comp Computable.fst) + have hi : Computable (fun p : ((Parameters × Entry) × ℕ) × ℕ => p.1.2) := + Computable.snd.comp Computable.fst + have hj : Computable (fun p : ((Parameters × Entry) × ℕ) × ℕ => p.2) := Computable.snd + have hm := (Primrec.list_getD false).to_comp.comp (Computable.fst.comp ha) hj + have he := computable_entry.comp + ((computable_rows.comp (Computable.snd.comp ha)).pair (hi.pair hj)) + have hb := Primrec.or.to_comp.comp hm (Primrec.not.to_comp.comp he) + have hM : Computable (fun p : (Parameters × Entry) × ℕ => universeSize p.1.1) := + computable_universeSize.comp (Computable.fst.comp Computable.fst) + have hrow := (EffectiveScan.computable_boundedAll + (p := fun p : (Parameters × Entry) × ℕ => fun j => + p.1.2.1.getD j false || !entry (rows p.1.2.2) p.2 j) hb).comp + (Computable.id.pair hM) + have hr : Computable (fun p : Parameters × Entry => rowRank p.1) := + computable_rowRank.comp Computable.fst + have hall := (EffectiveScan.computable_boundedAll + (p := fun p : Parameters × Entry => fun i => EffectiveScan.boundedAll + (fun j => p.2.1.getD j false || !entry (rows p.2.2) i j) (universeSize p.1)) + hrow).comp (Computable.id.pair hr) + exact hall.of_eq fun _ => rfl + +theorem computable_entryCheck : Computable₂ entryCheck := by + have hp : Computable (fun p : Parameters × Entry => p.1) := Computable.fst + have hm : Computable (fun p : Parameters × Entry => p.2.1) := + Computable.fst.comp Computable.snd + have hc : Computable (fun p : Parameters × Entry => p.2.2) := + Computable.snd.comp Computable.snd + have hlen := Primrec.eq.decide.to_comp.comp + (Computable.list_length.comp hm) (computable_universeSize.comp hp) + have hcard := Primrec.eq.decide.to_comp.comp + (computable_countTrue.comp hm) (computable_supportSize.comp hp) + have hw := Primrec.eq.decide.to_comp.comp + (computable_width.comp hc) (computable_universeSize.comp hp) + have hr := Primrec.eq.decide.to_comp.comp + (computable_rank.comp hc) (computable_rowRank.comp hp) + have hfinal := Primrec.and.to_comp.comp (computable_fullRank.comp hc) computable_offSupportCheck + have h := Primrec.and.to_comp.comp hlen (Primrec.and.to_comp.comp hcard + (Primrec.and.to_comp.comp hw (Primrec.and.to_comp.comp hr hfinal))) + exact h.of_eq fun _ => rfl + +theorem computable_incidenceCount : + Computable (fun p : CodeList × ℕ => p.1.countP (fun a => a.1.getD p.2 false)) := by + have hm : Computable (fun p : (CodeList × ℕ) × Entry => p.2.1) := + Computable.fst.comp Computable.snd + have hi : Computable (fun p : (CodeList × ℕ) × Entry => p.1.2) := + Computable.snd.comp Computable.fst + have hb := (Primrec.list_getD false).to_comp.comp hm hi + exact computable_list_countP (p := fun p : CodeList × ℕ => fun a : Entry => + a.1.getD p.2 false) Computable.fst hb.to₂ + +theorem computable_incidenceCheck : Computable₂ incidenceCheck := by + have hp : Computable (fun p : (Parameters × CodeList) × ℕ => p.1.1) := + Computable.fst.comp Computable.fst + have hL : Computable (fun p : (Parameters × CodeList) × ℕ => p.1.2) := + Computable.snd.comp Computable.fst + have hi : Computable (fun p : (Parameters × CodeList) × ℕ => p.2) := Computable.snd + have hleft := Primrec.nat_mul.to_comp.comp (computable_universeSize.comp hp) + (computable_incidenceCount.comp (hL.pair hi)) + have hright := Primrec.nat_mul.to_comp.comp + (Primrec.nat_mul.to_comp.comp (Computable.const 2) (computable_supportSize.comp hp)) + (computable_listLength.comp hp) + have hb := Primrec.nat_le.decide.to_comp.comp hleft hright + have hM : Computable (fun p : Parameters × CodeList => universeSize p.1) := + computable_universeSize.comp Computable.fst + have hall := (EffectiveScan.computable_boundedAll + (p := fun p : Parameters × CodeList => fun i => decide + (universeSize p.1 * p.2.countP (fun a => a.1.getD i false) ≤ + 2 * supportSize p.1 * listLength p.1)) hb).comp (Computable.id.pair hM) + exact hall.of_eq fun _ => rfl + +theorem computable_failureCount : Computable (fun p : CodeList × List Bool => + p.1.countP (fun a => !maskedFullRank a.2 p.2)) := by + have hc : Computable (fun p : (CodeList × List Bool) × Entry => p.2.2) := + Computable.snd.comp Computable.snd + have hd : Computable (fun p : (CodeList × List Bool) × Entry => p.1.2) := + Computable.snd.comp Computable.fst + have hb := Primrec.not.to_comp.comp (computable_maskedFullRank.comp hc hd) + exact computable_list_countP (p := fun p : CodeList × List Bool => fun a : Entry => + !maskedFullRank a.2 p.2) Computable.fst hb.to₂ + +theorem computable_restrictionCheck : Computable (fun p : (Parameters × CodeList) × List Bool => + restrictionCheck p.1.1 p.1.2 p.2) := by + have hp : Computable (fun p : (Parameters × CodeList) × List Bool => p.1.1) := + Computable.fst.comp Computable.fst + have hL : Computable (fun p : (Parameters × CodeList) × List Bool => p.1.2) := + Computable.snd.comp Computable.fst + have hd : Computable (fun p : (Parameters × CodeList) × List Bool => p.2) := Computable.snd + have hbound := primrec_rat_mul.to_comp.comp (computable_density.comp hp) + (primrec_rat_natCast.to_comp.comp (computable_universeSize.comp hp)) + have hcount := primrec_rat_natCast.to_comp.comp (computable_countTrue.comp hd) + have hdense := primrec_rat_le.decide.to_comp.comp hbound hcount + have hbad := primrec_rat_natCast.to_comp.comp (computable_failureCount.comp (hL.pair hd)) + have hbudget := primrec_rat_mul.to_comp.comp (computable_badFraction.comp hp) + (primrec_rat_natCast.to_comp.comp (computable_listLength.comp hp)) + have hsmall := primrec_rat_le.decide.to_comp.comp hbad hbudget + have hc := Primrec.or.to_comp.comp (Primrec.not.to_comp.comp hdense) hsmall + exact hc.of_eq fun _ => rfl + +/-- The complete candidate-list checker is a proved total computable function. -/ +theorem computable_check : Computable₂ check := by + have hp : Computable (fun p : Parameters × CodeList => p.1) := Computable.fst + have hL : Computable (fun p : Parameters × CodeList => p.2) := Computable.snd + have hlength := Primrec.eq.decide.to_comp.comp + (Computable.list_length.comp hL) (computable_listLength.comp hp) + have hep : Computable (fun p : (Parameters × CodeList) × Entry => p.1.1) := + Computable.fst.comp Computable.fst + have hea : Computable (fun p : (Parameters × CodeList) × Entry => p.2) := Computable.snd + have hentries := computable_list_all (p := fun p : Parameters × CodeList => entryCheck p.1) + hL (computable_entryCheck.comp hep hea) + have hwords := computable_words.comp (computable_universeSize.comp hp) + have hrestrictions := computable_list_all + (p := fun p : Parameters × CodeList => restrictionCheck p.1 p.2) + hwords computable_restrictionCheck + have hc := Primrec.and.to_comp.comp hlength (Primrec.and.to_comp.comp hentries + (Primrec.and.to_comp.comp computable_incidenceCheck hrestrictions)) + exact hc.of_eq fun _ => rfl + +theorem computablePred_good : ComputablePred (fun p : Parameters × CodeList => + Good (universeSize p.1) (supportSize p.1) (rowRank p.1) (listLength p.1) + (density p.1) (badFraction p.1) p.2) := by + have h : ComputablePred (fun p : Parameters × CodeList => check p.1 p.2 = true) := + ComputablePred.computable_iff.mpr ⟨_, computable_check, rfl⟩ + exact h.of_eq fun p => check_eq_true p.1 p.2 + +end Klr.SparseListSearch diff --git a/LeanPool/KLRandomness/SparseListSearchEffective.lean b/LeanPool/KLRandomness/SparseListSearchEffective.lean new file mode 100644 index 0000000000..66c961b77f --- /dev/null +++ b/LeanPool/KLRandomness/SparseListSearchEffective.lean @@ -0,0 +1,109 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.SparseListSearchComputable + +/-! +# Effective exhaustive search for sparse candidate lists + +The search enumerates ordinary natural-number encodings of finite lists and +runs the proved finite checker. It is partial recursive on all parameter +tuples, and it halts exactly when a list satisfying the mathematical sparse +contract exists. Thus a separate finite existence theorem supplies halting; +no classical choice of finite objects is assumed computable. +-/ + +@[expose] public section + +namespace Klr.SparseListSearch + +/-- Decode and check one possible finite list. -/ +def trial (p : Parameters) (n : ℕ) : Option CodeList := + (Encodable.decode n).bind fun L => if check p L then some L else none + +theorem computable_trial : Computable₂ trial := by + have hf : Computable₂ (fun p L => if check p L then some L else none) := by + have h := Computable.cond computable_check + (Computable.option_some.comp Computable.snd) (Computable.const none) + exact h.of_eq fun _ => by simp [Bool.cond_eq_ite] + exact Computable.bind_decode_iff.mpr hf + +/-- Actual partial-recursive exhaustive search through code-list encodings. -/ +def search (p : Parameters) : Part CodeList := Nat.rfindOpt (trial p) + +theorem partrec_search : Partrec search := Partrec.rfindOpt computable_trial + +theorem search_check {p : Parameters} {L : CodeList} (hL : L ∈ search p) : + check p L = true := by + obtain ⟨n, hn⟩ := Nat.rfindOpt_spec hL + simp only [trial, Option.mem_bind_iff] at hn + obtain ⟨K, _, hK⟩ := hn + split_ifs at hK with hv + · have he : K = L := Option.mem_some_iff.mp hK + simpa only [he] using hv + · simp at hK + +/-- Every returned list meets the full sparse-list contract. -/ +theorem search_spec {p : Parameters} {L : CodeList} (hL : L ∈ search p) : + Good (universeSize p) (supportSize p) (rowRank p) (listLength p) + (density p) (badFraction p) L := + (check_eq_true p L).mp (search_check hL) + +/-- Existence of a good finite code is precisely the halting condition of the actual search. -/ +theorem search_dom_iff (p : Parameters) : (search p).Dom ↔ + ∃ L : CodeList, Good (universeSize p) (supportSize p) (rowRank p) (listLength p) + (density p) (badFraction p) L := by + constructor + · intro h + obtain ⟨L, hL⟩ := Part.dom_iff_mem.mp h + exact ⟨L, search_spec hL⟩ + · rintro ⟨L, hL⟩ + apply Nat.rfindOpt_dom.mpr + refine ⟨Encodable.encode L, L, ?_⟩ + simp [trial, (check_eq_true p L).mpr hL] + +theorem exists_search_output_iff (p : Parameters) : + (∃ L : CodeList, L ∈ search p) ↔ + ∃ L : CodeList, Good (universeSize p) (supportSize p) (rowRank p) (listLength p) + (density p) (badFraction p) L := + Part.dom_iff_mem.symm.trans (search_dom_iff p) + +/-- Encode parameters with the canonical computability presentation of the rationals. +The unrelated default `Encodable ℚ` instance need not use this presentation. -/ +def encodeParameters (p : Parameters) : ℕ := + @Encodable.encode Parameters (inferInstance : Primcodable Parameters).toEncodable p + +theorem computable_encodeParameters : Computable encodeParameters := Computable.encode + +/-- One fixed Mathlib partial-recursive program implements the parameterized search. -/ +theorem exists_search_program : ∃ e : Nat.Partrec.Code, ∀ p : Parameters, + e.eval (encodeParameters p) = (search p).map Encodable.encode := by + obtain ⟨e, he⟩ := Nat.Partrec.Code.exists_code.mp partrec_search + refine ⟨e, fun p => ?_⟩ + rw [he] + dsimp only [encodeParameters] + rw [@Encodable.encodek Parameters (inferInstance : Primcodable Parameters).toEncodable p] + simp only [Part.coe_some, Part.bind_some] + +/-- Fix an actual program for the search, without making a program-size claim. -/ +noncomputable def searchProgram : Nat.Partrec.Code := Classical.choose exists_search_program + +theorem searchProgram_eval (p : Parameters) : + searchProgram.eval (encodeParameters p) = (search p).map Encodable.encode := + Classical.choose_spec exists_search_program p + +theorem searchProgram_dom_iff (p : Parameters) : + (searchProgram.eval (encodeParameters p)).Dom ↔ + ∃ L : CodeList, Good (universeSize p) (supportSize p) (rowRank p) (listLength p) + (density p) (badFraction p) L := by + rw [searchProgram_eval] + exact search_dom_iff p + +end Klr.SparseListSearch diff --git a/LeanPool/KLRandomness/SparseListWeights.lean b/LeanPool/KLRandomness/SparseListWeights.lean new file mode 100644 index 0000000000..08ca34a4ed --- /dev/null +++ b/LeanPool/KLRandomness/SparseListWeights.lean @@ -0,0 +1,158 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.SparseListConstruction +public import LeanPool.KLRandomness.SparseCandidateWeights +import Mathlib.Tactic.Linarith +import Mathlib.Tactic.Positivity +import Mathlib.Tactic.Ring + +/-! +# Small support weight in the executable sparse-list output + +The finite verifier's integer incidence inequalities and rational rank-failure +counts directly imply the deterministic support-weight bounds. All sums and +counts retain list multiplicities. The selected entry is an actual member of +the returned coded list; no reverse decoding into abstract candidates is needed. +-/ + +@[expose] public section + +namespace Klr.SparseListWeights + +open SparseListSearch SparseListCode SparseSearch +open scoped BigOperators + +variable {M m r J : ℕ} {τ θ : ℚ} {L : CodeList} + +/-- The actual pool support described by a coded entry's Boolean mask. -/ +def support (M : ℕ) (a : Entry) : Finset (Fin M) := maskSet M a.1 + +/-- The total weight on the support of a coded entry. -/ +def supportWeight (w : Fin M → ℝ) (a : Entry) : ℝ := ∑ i ∈ support M a, w i + +theorem supportWeight_nonneg (w : Fin M → ℝ) (hw : ∀ i, 0 ≤ w i) (a : Entry) : + 0 ≤ supportWeight w a := Finset.sum_nonneg fun i _ => hw i + +/-- List counts equal counts over the finite type of list positions. -/ +theorem countP_eq_card_filter_get {α : Type*} (l : List α) (p : α → Bool) : + l.countP p = + (Finset.univ.filter (fun j : Fin l.length => p (l.get j) = true)).card := by + simpa only [List.ofFn_get] using countP_ofFn l.get p + +/-- The sparse-support API counts the same occurrences as the executable checker. -/ +theorem incidence_eq_countP (L : CodeList) (i : Fin M) : + Sparse.incidence (fun j : Fin L.length => support M (L.get j)) i = + L.countP (fun a => a.1.getD i.val false) := by + classical + rw [countP_eq_card_filter_get] + unfold Sparse.incidence + congr 1 + ext j + simp [support] + +/-- The verifier's denominator-free incidence inequality gives the real-valued +incidence bound needed for deterministic averaging. -/ +theorem incidence_le_of_good (hL : Good M m r J τ θ L) (i : Fin M) : + (Sparse.incidence (fun j : Fin L.length => support M (L.get j)) i : ℝ) ≤ + 2 * ((m : ℝ) / M) * J := by + rw [incidence_eq_countP] + have hM : (0 : ℝ) < M := by exact_mod_cast (Nat.zero_lt_of_lt i.isLt) + have hi : (M : ℝ) * L.countP (fun a => a.1.getD i.val false) ≤ + 2 * (m : ℝ) * J := by + exact_mod_cast hL.2.2.1 i.val i.isLt + calc + _ ≤ (2 * (m : ℝ) * J) / M := (le_div_iff₀ hM).mpr (by nlinarith) + _ = _ := by ring + +/-- Average support weight in the actual checked code list. -/ +theorem average_supportWeight_le (hL : Good M m r J τ θ L) (hJ : 0 < J) + (w : Fin M → ℝ) (C : ℝ) (hw : ∀ i, 0 ≤ w i) + (hC : ∑ i, (w i) ^ 2 ≤ C) : + (∑ j : Fin L.length, supportWeight w (L.get j)) / J ≤ + (2 * ((m : ℝ) / M)) * Real.sqrt ((M : ℝ) * C) := by + have hlen : 0 < L.length := by rw [hL.1]; exact hJ + have : Nonempty (Fin L.length) := ⟨⟨0, hlen⟩⟩ + have hi : ∀ i, (Sparse.incidence (fun j : Fin L.length => support M (L.get j)) i : ℝ) ≤ + (2 * ((m : ℝ) / M)) * Fintype.card (Fin L.length) := by + intro i + simpa only [Fintype.card_fin, hL.1] using incidence_le_of_good hL i + simpa only [supportWeight, Fintype.card_fin, hL.1] using + Sparse.average_support_weights_le (fun j : Fin L.length => support M (L.get j)) + w (2 * ((m : ℝ) / M)) C hw (by positivity) hi hC + +/-- A dense unread mask has a rank-preserving entry of small support weight +in every checked nonempty code list. -/ +theorem exists_rank_good_small_weight (hL : Good M m r J τ θ L) (hJ : 0 < J) + (hθ : θ < 1) (d : List Bool) (hd : d.length = M) + (hdense : τ * (M : ℚ) ≤ (d.countP id : ℚ)) + (w : Fin M → ℝ) (C : ℝ) (hw : ∀ i, 0 ≤ w i) + (hC : ∑ i, (w i) ^ 2 ≤ C) : + ∃ a ∈ L, maskedFullRank a.2 d = true ∧ supportWeight w a ≤ + ((2 * ((m : ℝ) / M)) / (1 - (θ : ℝ))) * Real.sqrt ((M : ℝ) * C) := by + classical + let G := {j : Fin L.length // maskedFullRank (L.get j).2 d = true} + have hGcard : Fintype.card G = L.countP (fun a => maskedFullRank a.2 d) := by + simpa only [G, Fintype.card_subtype] using + (countP_eq_card_filter_get L (fun a => maskedFullRank a.2 d)).symm + have hpartition : L.countP (fun a => !maskedFullRank a.2 d) + Fintype.card G = J := by + rw [hGcard, ← hL.1] + simpa [Nat.add_comm] using + (List.length_eq_countP_add_countP (fun a : Entry => maskedFullRank a.2 d) (l := L)).symm + have hpartition' : (L.countP (fun a => !maskedFullRank a.2 d) : ℝ) + + Fintype.card G = J := by exact_mod_cast hpartition + have hbad : (L.countP (fun a => !maskedFullRank a.2 d) : ℝ) ≤ (θ : ℝ) * J := by + exact_mod_cast hL.2.2.2 d hd hdense + have hgood : (1 - (θ : ℝ)) * J ≤ (Fintype.card G : ℝ) := by linarith + have hθpos : 0 < 1 - (θ : ℝ) := by exact_mod_cast (sub_pos.mpr hθ) + have hJpos : (0 : ℝ) < J := by exact_mod_cast hJ + have hGpos : 0 < Fintype.card G := by + have h := (mul_pos hθpos hJpos).trans_le hgood + exact_mod_cast h + have : Nonempty G := Fintype.card_pos_iff.mp hGpos + have hδ : 0 ≤ 2 * ((m : ℝ) / M) := by positivity + have hi : ∀ i, (Sparse.incidence (fun j : G => support M (L.get j.val)) i : ℝ) ≤ + ((2 * ((m : ℝ) / M)) / (1 - (θ : ℝ))) * Fintype.card G := by + intro i + have hi0 : (Sparse.incidence (fun j : G => support M (L.get j.val)) i : ℝ) ≤ + (Sparse.incidence (fun j : Fin L.length => support M (L.get j)) i : ℝ) := by + exact_mod_cast SparseCandidateWeights.incidence_subtype_le + (fun j : Fin L.length => support M (L.get j)) + (fun j => maskedFullRank (L.get j).2 d = true) i + calc + _ ≤ 2 * ((m : ℝ) / M) * J := hi0.trans (incidence_le_of_good hL i) + _ ≤ _ := by + rw [div_mul_eq_mul_div] + apply (le_div_iff₀ hθpos).mpr + nlinarith [mul_le_mul_of_nonneg_left hgood hδ] + obtain ⟨j, hj⟩ := Sparse.exists_small_support (fun j : G => support M (L.get j.val)) + w ((2 * ((m : ℝ) / M)) / (1 - (θ : ℝ))) C hw + (div_nonneg hδ hθpos.le) hi hC + exact ⟨L.get j.val, List.get_mem L j.val, j.property, + by simpa only [supportWeight, Fintype.card_fin] using hj⟩ + +/-- The choice theorem applies directly to every output of the actual partial-recursive +construction, with the paper's polynomial pool and support sizes. -/ +theorem exists_rank_good_small_weight_of_construct {τ θ : ℚ} {r : ℕ} {L : CodeList} + (hL : L ∈ SparseListConstruction.construct τ θ r) (hr : 0 < r) (hθ : θ < 1) + (d : List Bool) (hd : d.length = SparseParameters.blockSize r) + (hdense : τ * (SparseParameters.blockSize r : ℚ) ≤ (d.countP id : ℚ)) + (w : Fin (SparseParameters.blockSize r) → ℝ) (C : ℝ) (hw : ∀ i, 0 ≤ w i) + (hC : ∑ i, (w i) ^ 2 ≤ C) : + ∃ a ∈ L, maskedFullRank a.2 d = true ∧ supportWeight w a ≤ + ((2 * ((SparseParameters.supportSize r : ℝ) / SparseParameters.blockSize r)) / + (1 - (θ : ℝ))) * Real.sqrt ((SparseParameters.blockSize r : ℝ) * C) := by + have hJ : 0 < SparseParameters.listSize r := by + unfold SparseParameters.listSize SparseParameters.blockSize + positivity + exact exists_rank_good_small_weight (SparseListConstruction.construct_spec hL) + hJ hθ d hd hdense w C hw hC + +end Klr.SparseListWeights diff --git a/LeanPool/KLRandomness/SparseParameters.lean b/LeanPool/KLRandomness/SparseParameters.lean new file mode 100644 index 0000000000..3f481c5e49 --- /dev/null +++ b/LeanPool/KLRandomness/SparseParameters.lean @@ -0,0 +1,160 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import Mathlib.Analysis.SpecialFunctions.Exp +import Mathlib.Tactic.Linarith +import Mathlib.Tactic.NormNum +import Mathlib.Tactic.Positivity +import Mathlib.Tactic.Ring + +/-! +# Eventual numerical bounds for sparse candidate lists + +The polynomial choices `M = r^8`, `m = r^2`, and `J = M^3` satisfy the +support, rank, and finite-list concentration estimates for every fixed +positive support density and error tolerance once `r` is sufficiently +large. The assertions here contain no probabilistic hypotheses. +-/ + +@[expose] public section + +namespace Klr.SparseParameters + +open Filter +open scoped Topology + +/-- The block length. -/ +def blockSize (r : ℕ) : ℕ := r ^ 8 + +/-- The number of columns in a support. -/ +def supportSize (r : ℕ) : ℕ := r ^ 2 + +/-- The number of independent candidates in a list. -/ +def listSize (r : ℕ) : ℕ := (blockSize r) ^ 3 + +theorem tendsto_nat_power (n : ℕ) (hn : n ≠ 0) : + Tendsto (fun r : ℕ => ((r ^ n : ℕ) : ℝ)) atTop atTop := by + simpa only [Function.comp_def, Nat.cast_pow] using + (tendsto_pow_atTop (α := ℝ) hn).comp tendsto_natCast_atTop_atTop + +theorem tendsto_blockSize : Tendsto (fun r => (blockSize r : ℝ)) atTop atTop := + tendsto_nat_power 8 (by decide) + +theorem tendsto_supportSize : Tendsto (fun r => (supportSize r : ℝ)) atTop atTop := + tendsto_nat_power 2 (by decide) + +/-- All elementary size hypotheses hold already from `r = 2` onward. -/ +theorem basic_bounds {r : ℕ} (hr : 2 ≤ r) : + 2 ≤ supportSize r ∧ supportSize r ≤ blockSize r ∧ r + 1 ≤ supportSize r := by + refine ⟨?_, ?_, ?_⟩ + · dsimp [supportSize] + nlinarith + · exact pow_le_pow_right' (by omega : 1 ≤ r) (by norm_num : 2 ≤ 8) + · dsimp [supportSize] + nlinarith + +theorem eventually_basic_bounds : + ∀ᶠ r : ℕ in atTop, + 2 ≤ supportSize r ∧ supportSize r ≤ blockSize r ∧ r + 1 ≤ supportSize r := + (eventually_ge_atTop 2).mono fun _ hr => basic_bounds hr + +/-- The expected unread support size eventually dominates four times the +number of rows, for every fixed positive density. -/ +theorem eventually_support_margin (τ : ℝ) (hτ : 0 < τ) : + ∀ᶠ r : ℕ in atTop, 4 * (r : ℝ) ≤ τ * (supportSize r : ℝ) := by + have h := (tendsto_natCast_atTop_atTop (R := ℝ)).eventually (eventually_ge_atTop (4 / τ)) + filter_upwards [h] with r hr + have hm := mul_le_mul_of_nonneg_right ((div_le_iff₀ hτ).mp hr) (Nat.cast_nonneg r : (0 : ℝ) ≤ r) + simpa [supportSize, pow_two, mul_assoc, mul_comm, mul_left_comm] using hm + +/-- The genuine one-candidate failure bound tends to zero. -/ +theorem tendsto_single_failure (τ : ℝ) (hτ : 0 < τ) : + Tendsto (fun r : ℕ => + 4 / (τ * (supportSize r : ℝ)) + 2 * (1 / 2 : ℝ) ^ r) atTop (𝓝 0) := by + have hden : Tendsto (fun r => τ * (supportSize r : ℝ)) atTop atTop := + tendsto_supportSize.const_mul_atTop hτ + have hi := hden.inv_tendsto_atTop.const_mul (4 : ℝ) + have hp := (tendsto_pow_atTop_nhds_zero_of_lt_one + (by norm_num : (0 : ℝ) ≤ 1 / 2) (by norm_num : (1 / 2 : ℝ) < 1)).const_mul (2 : ℝ) + simpa [div_eq_mul_inv] using hi.add hp + +theorem eventually_single_failure_le (τ θ : ℝ) (hτ : 0 < τ) (hθ : 0 < θ) : + ∀ᶠ r : ℕ in atTop, + 4 / (τ * (supportSize r : ℝ)) + 2 * (1 / 2 : ℝ) ^ r ≤ θ / 4 := + (tendsto_single_failure τ hτ).eventually_le_const (by positivity) + +/-- Once both negative exponents dominate `-M`, the two union-bound terms +are bounded by the familiar exponential tail. -/ +theorem union_bound_le_simple {M m θ : ℝ} (hM : 0 ≤ M) + (hθ : 8 ≤ θ * M ^ 2) (hm : 6 ≤ m * M) : + Real.exp (M - θ * M ^ 3 / 4) + M * Real.exp (-m * M ^ 2 / 6) ≤ + Real.exp (-M) + M * Real.exp (-M) := by + have hθM := mul_le_mul_of_nonneg_right hθ hM + have hmM := mul_le_mul_of_nonneg_right hm hM + apply add_le_add + · apply Real.exp_le_exp.mpr + nlinarith + · apply mul_le_mul_of_nonneg_left _ hM + apply Real.exp_le_exp.mpr + nlinarith + +/-- The total finite-list failure bound tends to zero for the polynomial +parameter choices. This is the numerical final step of the probabilistic +existence argument. -/ +theorem tendsto_list_failure (θ : ℝ) (hθ : 0 < θ) : + Tendsto (fun r : ℕ => + Real.exp ((blockSize r : ℝ) - θ * (listSize r : ℝ) / 4) + + (blockSize r : ℝ) * + Real.exp (-(supportSize r : ℝ) * (blockSize r : ℝ) ^ 2 / 6)) + atTop (𝓝 0) := by + have hsimple : Tendsto (fun r : ℕ => + Real.exp (-(blockSize r : ℝ)) + + (blockSize r : ℝ) * Real.exp (-(blockSize r : ℝ))) atTop (𝓝 0) := by + have he := Real.tendsto_exp_neg_atTop_nhds_zero.comp tendsto_blockSize + have hp := (Real.tendsto_pow_mul_exp_neg_atTop_nhds_zero 1).comp tendsto_blockSize + simpa using he.add hp + have hθlim : Tendsto (fun r : ℕ => θ * (blockSize r : ℝ) ^ 2) atTop atTop := + ((tendsto_pow_atTop (α := ℝ) (by decide : 2 ≠ 0)).comp tendsto_blockSize).const_mul_atTop hθ + have hmlim : Tendsto (fun r : ℕ => (supportSize r : ℝ) * (blockSize r : ℝ)) atTop atTop := by + convert tendsto_nat_power 10 (by decide) using 1 + ext r + simp only [supportSize, blockSize, Nat.cast_pow] + ring + apply squeeze_zero' (Eventually.of_forall fun r => by positivity) _ hsimple + filter_upwards [hθlim.eventually (eventually_ge_atTop 8), + hmlim.eventually (eventually_ge_atTop 6)] with r hθr hmr + simpa [listSize] using union_bound_le_simple + (Nat.cast_nonneg (blockSize r)) hθr hmr + +theorem eventually_list_failure_lt_one (θ : ℝ) (hθ : 0 < θ) : + ∀ᶠ r : ℕ in atTop, + Real.exp ((blockSize r : ℝ) - θ * (listSize r : ℝ) / 4) + + (blockSize r : ℝ) * + Real.exp (-(supportSize r : ℝ) * (blockSize r : ℝ) ^ 2 / 6) < 1 := + (tendsto_list_failure θ hθ).eventually_lt_const (by norm_num) + +/-- Every numerical premise of the sparse finite-list construction holds +simultaneously for all sufficiently large row counts. -/ +theorem eventually_candidate_parameters (τ θ : ℝ) (hτ : 0 < τ) (hθ : 0 < θ) : + ∀ᶠ r : ℕ in atTop, + 2 ≤ supportSize r ∧ + supportSize r ≤ blockSize r ∧ + r + 1 ≤ supportSize r ∧ + 4 * (r : ℝ) ≤ τ * (supportSize r : ℝ) ∧ + 4 / (τ * (supportSize r : ℝ)) + 2 * (1 / 2 : ℝ) ^ r ≤ θ / 4 ∧ + Real.exp ((blockSize r : ℝ) - θ * (listSize r : ℝ) / 4) + + (blockSize r : ℝ) * + Real.exp (-(supportSize r : ℝ) * (blockSize r : ℝ) ^ 2 / 6) < 1 := by + filter_upwards [eventually_basic_bounds, eventually_support_margin τ hτ, + eventually_single_failure_le τ θ hτ hθ, eventually_list_failure_lt_one θ hθ] + with r hr hmargin hsingle hlist + exact ⟨hr.1, hr.2.1, hr.2.2, hmargin, hsingle, hlist⟩ + +end Klr.SparseParameters diff --git a/LeanPool/KLRandomness/SparseSearchMask.lean b/LeanPool/KLRandomness/SparseSearchMask.lean new file mode 100644 index 0000000000..4b905a4b31 --- /dev/null +++ b/LeanPool/KLRandomness/SparseSearchMask.lean @@ -0,0 +1,148 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.SparseSearchRank + +/-! +# Computable rank tests after restricting the columns + +A finite Boolean mask selects columns of the coded matrix. Zeroing its other +columns is a concrete computation, and the certificate-free rank checker on +this new code agrees with surjectivity of the actual restricted column map. +-/ + +@[expose] public section + +namespace Klr.SparseSearch + +open AffineCode FiniteMeasure RandomMatrix + +/-- Evaluate a function at the first `n` natural numbers, retaining its +external computation parameter. -/ +def tabulate {β : Type*} (f : ℕ → β) (n : ℕ) : List β := (List.range n).map f + +theorem getD_tabulate {β : Type*} (f : ℕ → β) {n i : ℕ} (hi : i < n) (b : β) : + (tabulate f n).getD i b = f i := by + simp [tabulate, List.getD_eq_getElem?_getD, hi] + +theorem computable_tabulate {α β : Type*} [Primcodable α] [Primcodable β] + {f : α → ℕ → β} (hf : Computable₂ f) : + Computable (fun p : α × ℕ => tabulate (f p.1) p.2) := by + have hs : Computable₂ (fun (a : α × ℕ) (p : ℕ × List β) => p.2 ++ [f a.1 p.1]) := + (Computable.list_concat.comp (Computable.snd.comp Computable.snd) + (hf.comp (Computable.fst.comp Computable.fst) + (Computable.fst.comp Computable.snd))).to₂ + apply (Computable.nat_rec Computable.snd (Computable.const []) hs).of_eq + intro a + induction a.2 with + | zero => rfl + | succ n ih => + simpa only [tabulate, Nat.rec_add_one, List.range_succ, List.map_append, + List.map_cons, List.map_nil] using congrArg (fun s => s ++ [f a.1 n]) ih + +/-- Zero every column whose mask bit is false. The result is a rectangular +Boolean matrix, irrespective of missing entries in the original code. -/ +def maskCode (c : Data) (d : List Bool) : Data := + (c.1, (tabulate (fun i => tabulate + (fun j => entry (rows c) i j && d.getD j false) (width c)) (rank c), + (syndrome c, certificate c))) + +@[simp] theorem width_maskCode (c : Data) (d : List Bool) : width (maskCode c d) = width c := rfl +@[simp] theorem rank_maskCode (c : Data) (d : List Bool) : rank (maskCode c d) = rank c := rfl + +theorem computable_maskCode : Computable₂ maskCode := by + have hc : Computable (fun p : ((Data × List Bool) × ℕ) × ℕ => p.1.1.1) := + Computable.fst.comp (Computable.fst.comp Computable.fst) + have hd : Computable (fun p : ((Data × List Bool) × ℕ) × ℕ => p.1.1.2) := + Computable.snd.comp (Computable.fst.comp Computable.fst) + have hi : Computable (fun p : ((Data × List Bool) × ℕ) × ℕ => p.1.2) := + Computable.snd.comp Computable.fst + have hj : Computable (fun p : ((Data × List Bool) × ℕ) × ℕ => p.2) := Computable.snd + have he := computable_entry.comp ((computable_rows.comp hc).pair (hi.pair hj)) + have hb := (Primrec.list_getD false).to_comp.comp hd hj + have hrow := (computable_tabulate + (f := fun p : (Data × List Bool) × ℕ => fun j => + entry (rows p.1.1) p.2 j && p.1.2.getD j false) + (Primrec.and.to_comp.comp he hb)).comp + (Computable.id.pair (computable_width.comp (Computable.fst.comp Computable.fst))) + have hrows := (computable_tabulate + (f := fun p : Data × List Bool => fun i => tabulate + (fun j => entry (rows p.1) i j && p.2.getD j false) (width p.1)) hrow).comp + (Computable.id.pair (computable_rank.comp Computable.fst)) + have hresult := (Computable.fst.comp Computable.fst).pair + (hrows.pair ((computable_syndrome.comp Computable.fst).pair + (computable_certificate.comp Computable.fst))) + exact hresult.of_eq fun _ => rfl + +theorem matrix_maskCode (c : Data) (d : List Bool) : + matrix (maskCode c d) = fun i j => if d.getD j.val false then matrix c i j else 0 := by + ext i j + change Fin (rank c) at i + change Fin (width c) at j + change boolEquivF2 ((tabulate (fun i => tabulate + (fun j => entry (rows c) i j && d.getD j false) (width c)) (rank c)).getD i.val [] + |>.getD j.val false) = _ + rw [getD_tabulate _ i.isLt, getD_tabulate _ j.isLt] + cases d.getD j.val false <;> simp [matrix] + +/-- The actual set of selected column indices. -/ +def selectedColumns (c : Data) (d : List Bool) : Finset (Fin (width c)) := + Finset.univ.filter (fun j => d.getD j.val false = true) + +@[simp] theorem mem_selectedColumns (c : Data) (d : List Bool) (j : Fin (width c)) : + j ∈ selectedColumns c d ↔ d.getD j.val false = true := by simp [selectedColumns] + +theorem mulVecLin_eq_columnMap {m r : ℕ} + (A : Matrix (Fin r) (Fin m) (ZMod 2)) : + A.mulVecLin = columnMap (fun j i => A i j) := by + ext x i + simp [columnMap, Matrix.mulVec, dotProduct, mul_comm] + +/-- Zeroing columns and dropping them have the same surjectivity behavior. -/ +theorem zero_columns_surjective_iff {K V ι : Type*} [Field K] [AddCommGroup V] + [Module K V] [Fintype ι] [DecidableEq ι] (B : ι → V) (T : Finset ι) : + Function.Surjective (columnMap (fun i => if i ∈ T then B i else 0) (K := K)) ↔ + Function.Surjective (restrictedMap B T (K := K)) := by + rw [← not_iff_not, not_surjective_iff_exists_annihilator, + restricted_not_surjective_iff] + constructor + · rintro ⟨φ, hφ, hB⟩ + refine ⟨φ, hφ, funext fun t => ?_⟩ + simpa [t.property] using hB t.val + · rintro ⟨φ, hφ, hB⟩ + refine ⟨φ, hφ, fun i => ?_⟩ + by_cases hi : i ∈ T + · simpa [hi] using congrFun hB ⟨i, hi⟩ + · simp [hi] + +/-- A computable check of full row rank on only the selected columns. -/ +def maskedFullRank (c : Data) (d : List Bool) : Bool := fullRank (maskCode c d) + +theorem computable_maskedFullRank : Computable₂ maskedFullRank := + (computable_fullRank.comp computable_maskCode).to₂ + +/-- The executable masked checker is precisely the restriction-rank predicate +needed in sparse-list verification. -/ +theorem maskedFullRank_eq_true (c : Data) (d : List Bool) : + maskedFullRank c d = true ↔ Function.Surjective + (restrictedMap (fun j i => matrix c i j) (selectedColumns c d) (K := ZMod 2)) := by + rw [maskedFullRank, fullRank_eq_true, mulVecLin_eq_columnMap] + have he : (fun j i => matrix (maskCode c d) i j) = + fun j => if j ∈ selectedColumns c d then (fun i => matrix c i j) else 0 := by + funext j i + change Fin (width c) at j + change Fin (rank c) at i + rw [matrix_maskCode] + simp only [mem_selectedColumns] + split_ifs <;> rfl + rw [he] + exact zero_columns_surjective_iff _ _ + +end Klr.SparseSearch diff --git a/LeanPool/KLRandomness/SparseSearchRank.lean b/LeanPool/KLRandomness/SparseSearchRank.lean new file mode 100644 index 0000000000..2219b78502 --- /dev/null +++ b/LeanPool/KLRandomness/SparseSearchRank.lean @@ -0,0 +1,200 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.AffineCodeCoverage +public import LeanPool.KLRandomness.RandomMatrixAlgebra + +/-! +# A computable full-row-rank test without certificates + +The checker exhaustively enumerates finite Boolean vectors and checks +surjectivity of the coded matrix. Both the enumeration and the finite loops +have proofs of computability. The correctness theorem identifies acceptance +with actual linear-map surjectivity, independently of the certificate field +of the affine code. +-/ + +@[expose] public section + +namespace Klr.SparseSearch + +open AffineCode FiniteMeasure + +/-- Explicit enumeration of all Boolean words of the requested length. -/ +def words : ℕ → List (List Bool) + | 0 => [[]] + | n + 1 => (words n).map (false :: ·) ++ (words n).map (true :: ·) + +theorem mem_words_iff (n : ℕ) (w : List Bool) : w ∈ words n ↔ w.length = n := by + induction n generalizing w with + | zero => simp [words] + | succ n ih => + cases w with + | nil => simp [words] + | cons b w => cases b <;> simp [words, List.mem_map, ih] + +theorem computable_words : Computable words := by + have hf : Computable (fun l : List (List Bool) => l.map (false :: ·)) := + (Primrec.list_map Primrec.id + (Primrec.list_cons.comp (Primrec.const false) Primrec.snd).to₂).to_comp + have ht : Computable (fun l : List (List Bool) => l.map (true :: ·)) := + (Primrec.list_map Primrec.id + (Primrec.list_cons.comp (Primrec.const true) Primrec.snd).to₂).to_comp + have hs : Computable₂ (fun (_ : ℕ) (p : ℕ × List (List Bool)) => + p.2.map (false :: ·) ++ p.2.map (true :: ·)) := + (Computable.list_append.comp (hf.comp (Computable.snd.comp Computable.snd)) + (ht.comp (Computable.snd.comp Computable.snd))).to₂ + apply (Computable.nat_rec Computable.id (Computable.const [[]]) hs).of_eq + intro n + induction n with + | zero => rfl + | succ n ih => + simpa only [id_eq, words, Nat.rec_add_one] using + congrArg (fun l => l.map (false :: ·) ++ l.map (true :: ·)) ih + +/-- Finite Boolean conjunction of a computable predicate, with a computable +list of arguments. -/ +theorem computable_list_all {α β : Type*} [Primcodable α] [Primcodable β] + [Inhabited β] {f : α → List β} {p : α → β → Bool} + (hf : Computable f) (hp : Computable₂ p) : + Computable (fun a => (f a).all (p a)) := by + have hg : Computable (fun a : α × ℕ => (f a.1).getD a.2 default) := + (Primrec.list_getD default).to_comp.comp (hf.comp Computable.fst) Computable.snd + have hc := (EffectiveScan.computable_boundedAll + (p := fun a i => p a ((f a).getD i default)) (hp.comp Computable.fst hg)).comp + (Computable.id.pair (Computable.list_length.comp hf)) + apply hc.of_eq + intro a + rw [Bool.eq_iff_iff, EffectiveScan.boundedAll_eq_true, List.all_eq_true, + List.forall_mem_iff_getElem] + constructor + · intro h i hi + simpa [List.getD_eq_getElem?_getD, hi] using h i hi + · intro h i hi + simpa [List.getD_eq_getElem?_getD, hi] using h i hi + +/-- Finite Boolean disjunction has the corresponding computability closure. -/ +theorem computable_list_any {α β : Type*} [Primcodable α] [Primcodable β] + [Inhabited β] {f : α → List β} {p : α → β → Bool} + (hf : Computable f) (hp : Computable₂ p) : + Computable (fun a => (f a).any (p a)) := by + have hc := Primrec.not.to_comp.comp + (computable_list_all hf (Primrec.not.to_comp.comp hp).to₂) + exact hc.of_eq fun _ => List.any_eq_not_all_not.symm + +/-- A word denotes a binary vector by zero-filling missing entries. -/ +def wordVector (n : ℕ) (w : List Bool) : Fin n → ZMod 2 := + fun i => boolEquivF2 (w.getD i.val false) + +@[simp] theorem wordVector_ofFn {n : ℕ} (v : Fin n → ZMod 2) : + wordVector n (List.ofFn (fun i => boolEquivF2.symm (v i))) = v := by + funext i + simp [wordVector] + +/-- Dot product over the two-element field of an encoded row and a bit list. -/ +def rowValue (c : Data) (x : List Bool) (i : ℕ) : Bool := + parity (fun j => entry (rows c) i j && x.getD j false) (width c) + +theorem value_rowValue (c : Data) (x : List Bool) (i : Fin (rank c)) : + boolEquivF2 (rowValue c x i.val) = + (matrix c).mulVecLin (wordVector (width c) x) i := by + simp [rowValue, value_parity, value_and, matrix, wordVector, + Matrix.mulVec, dotProduct] + +theorem computable_rowValue : + Computable (fun p : (Data × List Bool) × ℕ => rowValue p.1.1 p.1.2 p.2) := by + have hd : Computable (fun p : ((Data × List Bool) × ℕ) × ℕ => p.1.1.1) := + Computable.fst.comp (Computable.fst.comp Computable.fst) + have hx : Computable (fun p : ((Data × List Bool) × ℕ) × ℕ => p.1.1.2) := + Computable.snd.comp (Computable.fst.comp Computable.fst) + have hi : Computable (fun p : ((Data × List Bool) × ℕ) × ℕ => p.1.2) := + Computable.snd.comp Computable.fst + have hj : Computable (fun p : ((Data × List Bool) × ℕ) × ℕ => p.2) := Computable.snd + have he := computable_entry.comp ((computable_rows.comp hd).pair (hi.pair hj)) + have hb := (Primrec.list_getD false).to_comp.comp hx hj + have hc := (computable_parity + (p := fun p : (Data × List Bool) × ℕ => fun j => + entry (rows p.1.1) p.2 j && p.1.2.getD j false) + (Primrec.and.to_comp.comp he hb)).comp + (Computable.id.pair (computable_width.comp (Computable.fst.comp Computable.fst))) + exact hc.of_eq fun _ => rfl + +/-- Check the entire coded equation `A x = y` by a bounded row loop. -/ +def mapsTo (c : Data) (x y : List Bool) : Bool := + EffectiveScan.boundedAll (fun i => decide (rowValue c x i = y.getD i false)) (rank c) + +theorem mapsTo_eq_true (c : Data) (x y : List Bool) : mapsTo c x y = true ↔ + (matrix c).mulVecLin (wordVector (width c) x) = wordVector (rank c) y := by + rw [mapsTo, EffectiveScan.boundedAll_eq_true] + constructor + · intro h + funext i + rw [← value_rowValue, (of_decide_eq_true (h i.val i.isLt))] + rfl + · intro h i hi + apply decide_eq_true + apply boolEquivF2.injective + exact (value_rowValue c x ⟨i, hi⟩).trans (congrFun h ⟨i, hi⟩) + +theorem computable_mapsTo : + Computable (fun p : Data × (List Bool × List Bool) => mapsTo p.1 p.2.1 p.2.2) := by + have hd : Computable (fun p : (Data × (List Bool × List Bool)) × ℕ => p.1.1) := + Computable.fst.comp Computable.fst + have hx : Computable (fun p : (Data × (List Bool × List Bool)) × ℕ => p.1.2.1) := + Computable.fst.comp (Computable.snd.comp Computable.fst) + have hy : Computable (fun p : (Data × (List Bool × List Bool)) × ℕ => p.1.2.2) := + Computable.snd.comp (Computable.snd.comp Computable.fst) + have hi : Computable (fun p : (Data × (List Bool × List Bool)) × ℕ => p.2) := Computable.snd + have hl := computable_rowValue.comp ((hd.pair hx).pair hi) + have hr := (Primrec.list_getD false).to_comp.comp hy hi + have hp := Primrec.eq.decide.to_comp.comp hl hr + have hc := (EffectiveScan.computable_boundedAll + (p := fun p : Data × (List Bool × List Bool) => fun i => + decide (rowValue p.1 p.2.1 i = p.2.2.getD i false)) hp).comp + (Computable.id.pair (computable_rank.comp Computable.fst)) + exact hc.of_eq fun _ => rfl + +/-- A finite, certificate-free exhaustive surjectivity checker. -/ +def fullRank (c : Data) : Bool := + (words (rank c)).all (fun y => (words (width c)).any (fun x => mapsTo c x y)) + +theorem computable_fullRank : Computable fullRank := by + have hf : Computable (fun p : Data × List Bool => words (width p.1)) := + computable_words.comp (computable_width.comp Computable.fst) + have hp : Computable₂ (fun p : Data × List Bool => fun x => mapsTo p.1 x p.2) := + (computable_mapsTo.comp ((Computable.fst.comp Computable.fst).pair + (Computable.snd.pair (Computable.snd.comp Computable.fst)))).to₂ + have hi := computable_list_any hf hp + exact computable_list_all (computable_words.comp computable_rank) hi.to₂ + +/-- The executable checker decides actual full row rank of the coded matrix. -/ +theorem fullRank_eq_true (c : Data) : + fullRank c = true ↔ Function.Surjective (matrix c).mulVecLin := by + simp only [fullRank, List.all_eq_true, List.any_eq_true] + constructor + · intro h v + let y := List.ofFn (fun i => boolEquivF2.symm (v i)) + have hy : y ∈ words (rank c) := (mem_words_iff _ _).mpr List.length_ofFn + obtain ⟨x, _, hx⟩ := h y hy + exact ⟨wordVector (width c) x, by simpa [y] using (mapsTo_eq_true c x y).mp hx⟩ + · intro h y _ + obtain ⟨v, hv⟩ := h (wordVector (rank c) y) + let x := List.ofFn (fun i => boolEquivF2.symm (v i)) + refine ⟨x, (mem_words_iff _ _).mpr List.length_ofFn, ?_⟩ + apply (mapsTo_eq_true c x y).mpr + simpa [x] using hv + +theorem computablePred_fullRowRank : + ComputablePred (fun c : Data => Function.Surjective (matrix c).mulVecLin) := by + have hc : ComputablePred (fun c => fullRank c = true) := + ComputablePred.computable_iff.mpr ⟨fullRank, computable_fullRank, rfl⟩ + exact hc.of_eq fullRank_eq_true + +end Klr.SparseSearch diff --git a/LeanPool/KLRandomness/Splitting.lean b/LeanPool/KLRandomness/Splitting.lean new file mode 100644 index 0000000000..1ba457af88 --- /dev/null +++ b/LeanPool/KLRandomness/Splitting.lean @@ -0,0 +1,83 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.SplittingWitness +public import LeanPool.KLRandomness.SplittingScheduler + +/-! +# The even/odd splitting property of KL randomness + +This is the instance of the Merkle--Miller--Nies--Reimann--Stephan splitting +theorem needed for base-four separation. The proof constructs a rational +source run explicitly and uses the repository's proved totalization theorem. +No equivalence with an external partial-real betting convention is assumed. +-/ + +@[expose] public section + +namespace Klr + +namespace Splitting + +theorem not_random_of_witness_comparison (side : Bool) (X : Cantor) + (O T : MartinLofTest) (hO : O.Fails (SplittingScheduler.oracle side X)) + (hT : T.Fails (SplittingScheduler.target side X)) + (hcomp : ∀ N, ∃ m ≥ N, + witnessTime T (SplittingScheduler.target side X) hT m ≤ + witnessTime O (SplittingScheduler.oracle side X) hO m) : + ¬KolmogorovLovelandRandom X := by + let d := family T (witnessTime O (SplittingScheduler.oracle side X) hO) + apply SplittingScheduler.not_kolmogorovLovelandRandom_of_bets side + (primrec_ready O.code).to_comp (computable_bet O.code T.code) X + d.reserveValue d.stake d.reserveValue_nil d.reserve_positive d.stake_legal + d.reserveValue_snoc + · exact eventually_ready O (SplittingScheduler.oracle side X) hO + · intro m n hready + exact bet_correct O T (SplittingScheduler.oracle side X) hO m + (ScanRule.inputPrefix (SplittingScheduler.target side X) n) + (by simpa only [ScanRule.length_inputPrefix] using hready) + · exact reserve_unbounded O T _ _ hO hT hcomp + +end Splitting + +/-- Splitting a KL-random sequence into its even and odd coordinates leaves +at least one Martin-Löf-random half. -/ +theorem kolmogorovLovelandRandom_even_or_odd (X : Cantor) + (hX : KolmogorovLovelandRandom X) : + MartinLofRandom (fun n => X (2 * n)) ∨ MartinLofRandom (fun n => X (2 * n + 1)) := by + classical + by_contra h + obtain ⟨he, ho⟩ := not_or.mp h + obtain ⟨E, hE⟩ := (not_martinLofRandom_iff _).mp he + obtain ⟨O, hO⟩ := (not_martinLofRandom_iff _).mp ho + have heven : SplittingScheduler.target false X = (fun n => X (2 * n)) := rfl + have hodd : SplittingScheduler.target true X = (fun n => X (2 * n + 1)) := rfl + have horacleEven : SplittingScheduler.oracle true X = (fun n => X (2 * n)) := rfl + have horacleOdd : SplittingScheduler.oracle false X = (fun n => X (2 * n + 1)) := rfl + rcases Splitting.witness_comparison + (Splitting.witnessTime E (fun n => X (2 * n)) hE) + (Splitting.witnessTime O (fun n => X (2 * n + 1)) hO) with hcomp | hcomp + · apply Splitting.not_random_of_witness_comparison false X O E + (by simpa only [horacleOdd] using hO) (by simpa only [heven] using hE) _ hX + simpa only [horacleOdd, heven] using hcomp + · apply Splitting.not_random_of_witness_comparison true X E O + (by simpa only [horacleEven] using hE) (by simpa only [hodd] using hO) _ hX + simpa only [horacleEven, hodd] using hcomp + +/-- Two failing half-tests are already enough to refute binary KL randomness. -/ +theorem not_kolmogorovLovelandRandom_of_halves_fail (T0 T1 : MartinLofTest) (X : Cantor) + (h0 : T0.Fails (fun n => X (2 * n))) (h1 : T1.Fails (fun n => X (2 * n + 1))) : + ¬KolmogorovLovelandRandom X := by + intro hX + rcases kolmogorovLovelandRandom_even_or_odd X hX with h | h + · exact h T0 h0 + · exact h T1 h1 + +end Klr diff --git a/LeanPool/KLRandomness/SplittingClopen.lean b/LeanPool/KLRandomness/SplittingClopen.lean new file mode 100644 index 0000000000..7c6e46e6c6 --- /dev/null +++ b/LeanPool/KLRandomness/SplittingClopen.lean @@ -0,0 +1,265 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.MartinLof +public import LeanPool.KLRandomness.PoolAdviceComputable +public import LeanPool.KLRandomness.PoolAdviceMeasure +public import LeanPool.KLRandomness.BlockProductAnswer +import Mathlib.Tactic.NormNum +import Mathlib.Tactic.Positivity +import Mathlib.Tactic.Ring + +/-! +# Bounded clopen approximants and their rational martingales + +A bounded simulation of an effective-open code gives a finite-prefix event. +Its conditional probability is an exactly computable rational martingale. +These are the finite objects used by the KL splitting argument. +-/ + +@[expose] public section + +namespace Klr.Splitting + +open MeasureTheory SparseSearch RationalComputability +open scoped ENNReal + +/-- Check all prefixes of length at most the simulation budget. -/ +def accepts (c : Nat.Partrec.Code) (n t : ℕ) (s : List Bool) : Bool := + (List.range (t + 1)).any fun k => + (c.evaln t (Encodable.encode (n, s.take k))).isSome + +theorem accepts_iff (c : Nat.Partrec.Code) (n t : ℕ) (s : List Bool) : + accepts c n t s = true ↔ + ∃ k ≤ t, ∃ a, c.evaln t (Encodable.encode (n, s.take k)) = some a := by + simp only [accepts, List.any_eq_true, List.mem_range] + constructor + · rintro ⟨k, hk, h⟩ + change (c.evaln t (Encodable.encode (n, s.take k))).isSome = true at h + cases he : c.evaln t (Encodable.encode (n, s.take k)) with + | none => rw [he] at h; cases h + | some a => exact ⟨k, by omega, a, he⟩ + · rintro ⟨k, hk, a, ha⟩ + refine ⟨k, by omega, ?_⟩ + rw [ha] + rfl + +theorem accepts_take (c : Nat.Partrec.Code) (n t : ℕ) (s : List Bool) : + accepts c n t (s.take t) = accepts c n t s := by + rw [Bool.eq_iff_iff, accepts_iff, accepts_iff] + constructor <;> rintro ⟨k, hk, a, ha⟩ <;> refine ⟨k, hk, a, ?_⟩ + · simpa only [List.take_take, Nat.min_eq_left hk] using ha + · simpa only [List.take_take, Nat.min_eq_left hk] using ha + +theorem accepts_prefix (c : Nat.Partrec.Code) (n t d : ℕ) (hd : t ≤ d) + (X : Cantor) : + accepts c n t (ScanRule.inputPrefix X d) = + accepts c n t (ScanRule.inputPrefix X t) := by + rw [← accepts_take c n t, PoolAdvice.inputPrefix_take X hd] + +/-- The event discovered by time `t`, with all its cylinders truncated at depth `t`. -/ +def event (c : Nat.Partrec.Code) (n t : ℕ) : Set Cantor := + {X | accepts c n t (ScanRule.inputPrefix X t) = true} + +theorem measurableSet_event (c : Nat.Partrec.Code) (n t : ℕ) : + MeasurableSet (event c n t) := + measurableSet_prefix_event (fun s => accepts c n t s = true) t + +theorem event_subset (c : Nat.Partrec.Code) (n t : ℕ) : + event c n t ⊆ programOpen c n := by + intro X hX + obtain ⟨k, hk, a, ha⟩ := (accepts_iff _ _ _ _).mp hX + refine ⟨(ScanRule.inputPrefix X t).take k, ?_, ?_⟩ + · exact Part.dom_iff_mem.mpr ⟨a, Nat.Partrec.Code.evaln_sound ha⟩ + · rw [PoolAdvice.inputPrefix_take X hk] + exact ScanRule.mem_cylinder_inputPrefix X k + +theorem event_mono (c : Nat.Partrec.Code) (n : ℕ) {s t : ℕ} (hst : s ≤ t) : + event c n s ⊆ event c n t := by + intro X hX + obtain ⟨k, hk, a, ha⟩ := (accepts_iff _ _ _ _).mp hX + apply (accepts_iff _ _ _ _).mpr + refine ⟨k, hk.trans hst, a, ?_⟩ + rw [PoolAdvice.inputPrefix_take X hk] at ha + rw [PoolAdvice.inputPrefix_take X (hk.trans hst)] + exact Nat.Partrec.Code.evaln_mono hst ha + +theorem mem_programOpen_iff (c : Nat.Partrec.Code) (n : ℕ) (X : Cantor) : + X ∈ programOpen c n ↔ ∃ t, X ∈ event c n t := by + constructor + · rintro ⟨s, hs, hX⟩ + obtain ⟨a, ha⟩ := Part.dom_iff_mem.mp hs + obtain ⟨t, ht⟩ := Nat.Partrec.Code.evaln_complete.mp ha + refine ⟨max t s.length, (accepts_iff _ _ _ _).mpr ?_⟩ + refine ⟨s.length, Nat.le_max_right _ _, a, ?_⟩ + rw [PoolAdvice.inputPrefix_take X (Nat.le_max_right _ _), + (PoolAdvice.inputPrefix_eq_iff_mem_cylinder X s.length s rfl).mpr hX] + exact Nat.Partrec.Code.evaln_mono (Nat.le_max_left _ _) ht + · rintro ⟨t, ht⟩ + exact event_subset c n t ht + +theorem primrec_accepts : + Primrec (fun p : (Nat.Partrec.Code × (ℕ × ℕ)) × List Bool => + accepts p.1.1 p.1.2.1 p.1.2.2 p.2) := by + let α := (Nat.Partrec.Code × (ℕ × ℕ)) × List Bool + have hc : Primrec (fun p : α × ℕ => p.1.1.1) := + Primrec.fst.comp (Primrec.fst.comp Primrec.fst) + have hn : Primrec (fun p : α × ℕ => p.1.1.2.1) := + Primrec.fst.comp (Primrec.snd.comp (Primrec.fst.comp Primrec.fst)) + have ht : Primrec (fun p : α × ℕ => p.1.1.2.2) := + Primrec.snd.comp (Primrec.snd.comp (Primrec.fst.comp Primrec.fst)) + have hs : Primrec (fun p : α × ℕ => p.1.2) := + Primrec.snd.comp Primrec.fst + have hp := Primrec.list_take.comp Primrec.snd hs + have he := Nat.Partrec.Code.primrec_evaln.comp + ((ht.pair hc).pair (Primrec.encode.comp (hn.pair hp))) + have hb := Primrec.option_isSome.comp he + exact Primrec.list_any + (Primrec.list_range.comp (Primrec.succ.comp + (Primrec.snd.comp (Primrec.snd.comp Primrec.fst)))) hb.to₂ + +theorem computable_accepts : + Computable (fun p : (Nat.Partrec.Code × (ℕ × ℕ)) × List Bool => + accepts p.1.1 p.1.2.1 p.1.2.2 p.2) := primrec_accepts.to_comp + +/-- Exact conditional probability of the bounded event after a finite prefix. -/ +def clopenCapital (c : Nat.Partrec.Code) (n t : ℕ) (v : List Bool) : ℚ := + (2 : ℚ) ^ v.length * PoolAdvice.average (max t v.length) (fun s => + if accepts c n t s && decide (s.take v.length = v) then 1 else 0) + +theorem clopenCapital_eq_measure (c : Nat.Partrec.Code) (n t : ℕ) (v : List Bool) : + (clopenCapital c n t v : ℝ) = + (2 : ℝ) ^ v.length * fairCoin.real (event c n t ∩ cylinder v) := by + rw [clopenCapital, Rat.cast_mul, Rat.cast_pow, Rat.cast_ofNat, + PoolAdvice.average_eq_integral, + ← integral_indicator_one ((measurableSet_event c n t).inter (measurableSet_cylinder v))] + congr 1 + apply integral_congr_ae + filter_upwards [] with X + have hp := PoolAdvice.inputPrefix_take X (Nat.le_max_right t v.length) + have ha := accepts_prefix c n t (max t v.length) (Nat.le_max_left _ _) X + have he : (accepts c n t (ScanRule.inputPrefix X (max t v.length)) && + decide ((ScanRule.inputPrefix X (max t v.length)).take v.length = v)) = true ↔ + X ∈ event c n t ∩ cylinder v := by + simp only [Bool.and_eq_true, decide_eq_true_eq, hp, ha, + PoolAdvice.inputPrefix_eq_iff_mem_cylinder X v.length v rfl] + rfl + by_cases hX : X ∈ event c n t ∩ cylinder v + · simp [he.mpr hX, Set.indicator_of_mem hX] + · simp [mt he.mp hX, Set.indicator_of_notMem hX] + +theorem clopenCapital_nonneg (c : Nat.Partrec.Code) (n t : ℕ) (v : List Bool) : + 0 ≤ clopenCapital c n t v := by + apply (Rat.cast_nonneg (K := ℝ)).mp + rw [clopenCapital_eq_measure] + positivity + +theorem cylinder_snoc (v : List Bool) (b : Bool) : + cylinder (v ++ [b]) = cylinder v ∩ {X | X v.length = b} := by + rw [cylinder_eq_monotone_inputEvent, BlockProductAnswer.inputEvent_snoc, + ← cylinder_eq_monotone_inputEvent] + rfl + +theorem cylinder_children_union (v : List Bool) : + cylinder (v ++ [false]) ∪ cylinder (v ++ [true]) = cylinder v := by + rw [cylinder_snoc, cylinder_snoc] + ext X + cases h : X v.length <;> simp [h] + +theorem cylinder_children_disjoint (v : List Bool) : + Disjoint (cylinder (v ++ [false])) (cylinder (v ++ [true])) := by + rw [cylinder_snoc, cylinder_snoc] + exact Set.disjoint_left.mpr (fun X h₀ h₁ => Bool.false_ne_true (h₀.2.symm.trans h₁.2)) + +theorem clopenCapital_fair (c : Nat.Partrec.Code) (n t : ℕ) (v : List Bool) : + clopenCapital c n t (v ++ [false]) + clopenCapital c n t (v ++ [true]) = + 2 * clopenCapital c n t v := by + apply (Rat.cast_injective (α := ℝ)) + push_cast + rw [clopenCapital_eq_measure, clopenCapital_eq_measure, clopenCapital_eq_measure] + have hd : Disjoint (event c n t ∩ cylinder (v ++ [false])) + (event c n t ∩ cylinder (v ++ [true])) := + (cylinder_children_disjoint v).mono Set.inter_subset_right Set.inter_subset_right + have hm := measureReal_union (μ := fairCoin) hd + ((measurableSet_event c n t).inter (measurableSet_cylinder (v ++ [true]))) + rw [← Set.inter_union_distrib_left, cylinder_children_union] at hm + simp only [List.length_append, List.length_singleton, pow_succ] + rw [hm] + ring + +theorem clopenCapital_initial_le (T : MartinLofTest) (n t : ℕ) : + clopenCapital T.code n t [] ≤ (1 / 2 : ℚ) ^ n := by + apply (Rat.cast_le (K := ℝ)).mp + rw [clopenCapital_eq_measure] + simp only [List.length_nil, pow_zero, cylinder_nil, Set.inter_univ, one_mul] + push_cast + have h := ENNReal.toReal_mono (by finiteness : (1 / 2 : ℝ≥0∞) ^ n ≠ ∞) + ((measure_mono (event_subset T.code n t)).trans (T.measure_le n)) + simpa only [measureReal_def, ENNReal.toReal_pow, ENNReal.toReal_div, + ENNReal.toReal_one, ENNReal.toReal_ofNat] using h + +theorem clopenCapital_eq_one (c : Nat.Partrec.Code) (n t : ℕ) (X : Cantor) + (hX : X ∈ event c n t) {d : ℕ} (hd : t ≤ d) : + clopenCapital c n t (ScanRule.inputPrefix X d) = 1 := by + have hsub : cylinder (ScanRule.inputPrefix X d) ⊆ event c n t := by + intro Y hY + have hp := (PoolAdvice.inputPrefix_eq_iff_mem_cylinder Y d + (ScanRule.inputPrefix X d) (by simp)).mpr hY + change accepts c n t (ScanRule.inputPrefix Y t) = true + rw [← accepts_prefix c n t d hd Y, hp, accepts_prefix c n t d hd X] + exact hX + apply (Rat.cast_injective (α := ℝ)) + rw [clopenCapital_eq_measure, Set.inter_eq_right.mpr hsub] + simp only [measureReal_def, fairCoin_cylinder, ENNReal.toReal_pow, + ENNReal.toReal_div, ENNReal.toReal_one, ENNReal.toReal_ofNat, Rat.cast_one] + rw [← mul_pow] + norm_num + +theorem computable_clopenCapital : + Computable (fun p : (Nat.Partrec.Code × (ℕ × ℕ)) × List Bool => + clopenCapital p.1.1 p.1.2.1 p.1.2.2 p.2) := by + let α := (Nat.Partrec.Code × (ℕ × ℕ)) × List Bool + have hv : Computable (fun p : α × List Bool => p.1.2) := + Computable.snd.comp Computable.fst + have hlen : Computable (fun p : α => p.2.length) := + Computable.list_length.comp Computable.snd + have hacc : Computable (fun p : α × List Bool => + accepts p.1.1.1 p.1.1.2.1 p.1.1.2.2 p.2) := by + have hproj : Computable (fun p : α × List Bool => (p.1.1, p.2)) := + (Computable.fst.comp Computable.fst).pair Computable.snd + have hh := computable_accepts.comp hproj + exact hh + have hp : Computable (fun p : α × List Bool => p.2.take p.1.2.length) := + Primrec.list_take.to_comp.comp (Computable.list_length.comp hv) Computable.snd + have he : Computable (fun p : α × List Bool => decide (p.2.take p.1.2.length = p.1.2)) := + Primrec.eq.decide.to_comp.comp hp hv + have hb : Computable (fun p : α × List Bool => + accepts p.1.1.1 p.1.1.2.1 p.1.1.2.2 p.2 && decide (p.2.take p.1.2.length = p.1.2)) := + Primrec.and.to_comp.comp hacc he + have hi : Computable (fun p : α × List Bool => + if accepts p.1.1.1 p.1.1.2.1 p.1.1.2.2 p.2 && + decide (p.2.take p.1.2.length = p.1.2) then (1 : ℚ) else 0) := + (Computable.cond hb (Computable.const (1 : ℚ)) (Computable.const 0)).of_eq + (fun _ => by simp only [Bool.cond_eq_ite]) + have hdepth : Computable (fun p : α => max p.1.2.2 p.2.length) := + Primrec.nat_max.to_comp.comp + (Computable.snd.comp (Computable.snd.comp Computable.fst)) hlen + have hav : Computable (fun p : α => PoolAdvice.average (max p.1.2.2 p.2.length) + (fun s => if accepts p.1.1 p.1.2.1 p.1.2.2 s && + decide (s.take p.2.length = p.2) then (1 : ℚ) else 0)) := + PoolAdvice.computable_average hdepth hi.to₂ + have hpow : Computable (fun p : α => (2 : ℚ) ^ p.2.length) := by + apply (primrec_rat_natCast.to_comp.comp + (Computable.list_length.comp (computable_words.comp hlen))).of_eq + intro p + simp only [PoolAdvice.length_words, Nat.cast_pow, Nat.cast_ofNat] + exact primrec_rat_mul.to_comp.comp hpow hav + +end Klr.Splitting diff --git a/LeanPool/KLRandomness/SplittingReserve.lean b/LeanPool/KLRandomness/SplittingReserve.lean new file mode 100644 index 0000000000..970c0c46e8 --- /dev/null +++ b/LeanPool/KLRandomness/SplittingReserve.lean @@ -0,0 +1,251 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.EffectiveNormalization +public import Mathlib.Algebra.Order.Field.GeomSum +import Mathlib.Tactic.GCongr +import Mathlib.Tactic.Linarith +import Mathlib.Tactic.NormNum +import Mathlib.Tactic.Positivity +import Mathlib.Tactic.Ring + +/-! +# A rational reserve for small finite-event martingales + +Only finite sums are needed. At target length `n` the gambler uses the first +`2*n+6` accounts. Comparison with any larger finite sum bounds the cumulative +wager error by `1/32` and leaves a positive reserve. +-/ + +@[expose] public section + +namespace Klr.Splitting + +open scoped BigOperators + +/-- A sequence of nonnegative rational martingales with rapidly decreasing costs. -/ +structure SmallMartingales where + /-- Rational capital of each component martingale at a finite transcript. -/ + value : ℕ → List Bool → ℚ + nonneg : ∀ m v, 0 ≤ value m v + fair : ∀ m v, value m (v ++ [false]) + value m (v ++ [true]) = 2 * value m v + initial_le : ∀ m, value m [] ≤ (1 / 2 : ℚ) ^ (2 * m + 2) + +namespace SmallMartingales + +variable (d : SmallMartingales) + +theorem successor_le (m : ℕ) (v : List Bool) (b : Bool) : + d.value m (v ++ [b]) ≤ 2 * d.value m v := by + have hf := d.fair m v + have h₀ := d.nonneg m (v ++ [false]) + have h₁ := d.nonneg m (v ++ [true]) + cases b <;> linarith + +theorem value_le (m : ℕ) (v : List Bool) : + d.value m v ≤ (2 : ℚ) ^ v.length * d.value m [] := by + induction v using List.reverseRecOn with + | nil => simp + | append_singleton v b ih => + calc + d.value m (v ++ [b]) ≤ 2 * d.value m v := d.successor_le m v b + _ ≤ 2 * ((2 : ℚ) ^ v.length * d.value m []) := by gcongr + _ = _ := by simp [pow_succ]; ring + +theorem weighted_le (m : ℕ) (v : List Bool) : + (2 : ℚ) ^ m * d.value m v ≤ (2 : ℚ) ^ v.length * (1 / 2 : ℚ) ^ (m + 2) := by + have hpow : (2 : ℚ) ^ m * (1 / 2 : ℚ) ^ (2 * m + 2) = + (1 / 2 : ℚ) ^ (m + 2) := by + rw [show 2 * m + 2 = m + (m + 2) by omega, pow_add, ← mul_assoc, ← mul_pow] + norm_num + calc + _ ≤ (2 : ℚ) ^ m * ((2 : ℚ) ^ v.length * d.value m []) := by + gcongr + exact d.value_le m v + _ ≤ (2 : ℚ) ^ m * ((2 : ℚ) ^ v.length * (1 / 2 : ℚ) ^ (2 * m + 2)) := by + gcongr + exact d.initial_le m + _ = _ := by rw [mul_left_comm, hpow] + +/-- Weighted capital of the components below the given cutoff. -/ +def sumCapital (K : ℕ) (v : List Bool) : ℚ := + ∑ m ∈ Finset.range K, (2 : ℚ) ^ m * d.value m v + +@[simp] theorem sumCapital_zero (v : List Bool) : d.sumCapital 0 v = 0 := by + simp [sumCapital] + +theorem sumCapital_nonneg (K : ℕ) (v : List Bool) : 0 ≤ d.sumCapital K v := + Finset.sum_nonneg fun m _ => mul_nonneg (by positivity) (d.nonneg m v) + +theorem sumCapital_fair (K : ℕ) (v : List Bool) : + d.sumCapital K (v ++ [false]) + d.sumCapital K (v ++ [true]) = + 2 * d.sumCapital K v := by + simp only [sumCapital, ← Finset.sum_add_distrib, Finset.mul_sum] + apply Finset.sum_congr rfl + intro m hm + rw [← mul_add, d.fair m v] + ring + +theorem tail_nonneg (M K : ℕ) (hMK : M ≤ K) (v : List Bool) : + 0 ≤ d.sumCapital K v - d.sumCapital M v := by + unfold sumCapital + rw [← Finset.sum_Ico_eq_sub _ hMK] + exact Finset.sum_nonneg fun m _ => mul_nonneg (by positivity) (d.nonneg m v) + +theorem tail_le (M K : ℕ) (hMK : M ≤ K) (v : List Bool) : + d.sumCapital K v - d.sumCapital M v ≤ + (2 : ℚ) ^ v.length * (1 / 2 : ℚ) ^ (M + 1) := by + have hg := geom_sum_Ico_le_of_lt_one (K := ℚ) (m := M) (n := K) + (by norm_num : 0 ≤ (1 / 2 : ℚ)) (by norm_num : (1 / 2 : ℚ) < 1) + norm_num at hg + unfold sumCapital + rw [← Finset.sum_Ico_eq_sub _ hMK] + calc + _ ≤ ∑ m ∈ Finset.Ico M K, (2 : ℚ) ^ v.length * (1 / 2 : ℚ) ^ (m + 2) := + Finset.sum_le_sum fun m _ => d.weighted_le m v + _ = (2 : ℚ) ^ v.length * ((∑ m ∈ Finset.Ico M K, (1 / 2 : ℚ) ^ m) / 4) := by + simp only [pow_add, Finset.mul_sum, Finset.sum_div] + apply Finset.sum_congr rfl + intro m hm + ring + _ ≤ (2 : ℚ) ^ v.length * ((1 / 2 : ℚ) ^ M / 2) := by + apply mul_le_mul_of_nonneg_left _ (by positivity) + linarith + _ = _ := by rw [pow_succ]; ring + +theorem sumCapital_initial_le (K : ℕ) : d.sumCapital K [] ≤ 1 / 2 := by + simpa using d.tail_le 0 K (Nat.zero_le _) [] + +theorem term_le_sumCapital (K m : ℕ) (hm : m < K) (v : List Bool) : + (2 : ℚ) ^ m * d.value m v ≤ d.sumCapital K v := + Finset.single_le_sum (fun j _ => mul_nonneg (by positivity) (d.nonneg j v)) + (Finset.mem_range.mpr hm) + +/-- The finite precision increases faster than the target prefix length. -/ +def cutoff (n : ℕ) : ℕ := 2 * n + 6 + +theorem cutoff_mono {m n : ℕ} (h : m ≤ n) : cutoff m ≤ cutoff n := by + unfold cutoff + omega + +/-- Next signed stake of the sum with cutoff determined by the transcript length. -/ +def stake (v : List Bool) : ℚ := + (d.sumCapital (cutoff v.length) (v ++ [true]) - + d.sumCapital (cutoff v.length) (v ++ [false])) / 2 + +/-- Next signed stake of the sum with a fixed component cutoff. -/ +def referenceStake (K : ℕ) (v : List Bool) : ℚ := + (d.sumCapital K (v ++ [true]) - d.sumCapital K (v ++ [false])) / 2 + +theorem reference_snoc (K : ℕ) (v : List Bool) (b : Bool) : + d.sumCapital K (v ++ [b]) = d.sumCapital K v + answerSign b * d.referenceStake K v := by + have hf := d.sumCapital_fair K v + cases b <;> simp only [answerSign_false, answerSign_true, referenceStake] <;> linarith + +theorem stake_error (K : ℕ) (v : List Bool) (hK : cutoff v.length ≤ K) : + |d.stake v - d.referenceStake K v| ≤ (1 / 2 : ℚ) ^ (v.length + 6) := by + have hbound (b : Bool) : + d.sumCapital K (v ++ [b]) - d.sumCapital (cutoff v.length) (v ++ [b]) ≤ + (1 / 2 : ℚ) ^ (v.length + 6) := by + have h := d.tail_le (cutoff v.length) K hK (v ++ [b]) + have he : (2 : ℚ) ^ (v.length + 1) * (1 / 2 : ℚ) ^ (cutoff v.length + 1) = + (1 / 2 : ℚ) ^ (v.length + 6) := by + rw [show cutoff v.length + 1 = (v.length + 1) + (v.length + 6) by + unfold cutoff; omega, pow_add (1 / 2 : ℚ), ← mul_assoc, ← mul_pow] + norm_num + simpa only [List.length_append, List.length_singleton, he] using h + have h₀ := d.tail_nonneg (cutoff v.length) K hK (v ++ [false]) + have h₁ := d.tail_nonneg (cutoff v.length) K hK (v ++ [true]) + have hb₀ := hbound false + have hb₁ := hbound true + have hp : 0 ≤ (1 / 2 : ℚ) ^ (v.length + 6) := by positivity + rw [abs_le] + unfold stake referenceStake + constructor <;> linarith + +/-- Advance the transcript and add the signed return to the reserve account. -/ +def reserveStep (s : List Bool × ℚ) (b : Bool) : List Bool × ℚ := + (s.1 ++ [b], s.2 + answerSign b * d.stake s.1) + +/-- The transcript and capital of the combined account at the given time. -/ +def reserveAccount (v : List Bool) : List Bool × ℚ := + v.foldl d.reserveStep ([], 1) + +/-- Capital of the combined account after a finite transcript. -/ +def reserveValue (v : List Bool) : ℚ := (d.reserveAccount v).2 + +@[simp] theorem reserveAccount_snoc (v : List Bool) (b : Bool) : + d.reserveAccount (v ++ [b]) = d.reserveStep (d.reserveAccount v) b := by + simp [reserveAccount, List.foldl_append] + +theorem reserveAccount_prefix (v : List Bool) : (d.reserveAccount v).1 = v := by + induction v using List.reverseRecOn with + | nil => rfl + | append_singleton v b ih => simp [reserveStep, ih] + +@[simp] theorem reserveValue_nil : d.reserveValue [] = 1 := rfl + +theorem reserveValue_snoc (v : List Bool) (b : Bool) : + d.reserveValue (v ++ [b]) = d.reserveValue v + answerSign b * d.stake v := by + simp [reserveValue, reserveStep, reserveAccount_prefix] + +theorem reserve_error_geometric (v : List Bool) (K : ℕ) (hK : cutoff v.length ≤ K) : + |d.reserveValue v - (d.sumCapital K v + 1 - d.sumCapital K [])| ≤ + (1 / 32 : ℚ) * (1 - (1 / 2 : ℚ) ^ v.length) := by + induction v using List.reverseRecOn with + | nil => simp + | append_singleton v b ih => + have hK' : cutoff v.length ≤ K := + (cutoff_mono (by simp)).trans hK + have heq : + d.reserveValue (v ++ [b]) - (d.sumCapital K (v ++ [b]) + 1 - d.sumCapital K []) = + (d.reserveValue v - (d.sumCapital K v + 1 - d.sumCapital K [])) + + answerSign b * (d.stake v - d.referenceStake K v) := by + rw [reserveValue_snoc, reference_snoc] + ring + rw [heq] + calc + _ ≤ |d.reserveValue v - (d.sumCapital K v + 1 - d.sumCapital K [])| + + |answerSign b * (d.stake v - d.referenceStake K v)| := abs_add_le _ _ + _ = |d.reserveValue v - (d.sumCapital K v + 1 - d.sumCapital K [])| + + |d.stake v - d.referenceStake K v| := by simp [abs_mul] + _ ≤ (1 / 32 : ℚ) * (1 - (1 / 2 : ℚ) ^ v.length) + + (1 / 2 : ℚ) ^ (v.length + 6) := add_le_add (ih hK') (d.stake_error K v hK') + _ = _ := by simp only [List.length_append, List.length_singleton, pow_add]; ring + +theorem reserve_lower_sum (v : List Bool) (K : ℕ) (hK : cutoff v.length ≤ K) : + d.sumCapital K v + 15 / 32 ≤ d.reserveValue v := by + have h := (abs_le.mp (d.reserve_error_geometric v K hK)).1 + have hi := d.sumCapital_initial_le K + have hp : 0 ≤ (1 / 2 : ℚ) ^ v.length := by positivity + linarith + +theorem reserve_positive (v : List Bool) : 0 < d.reserveValue v := by + have h := d.reserve_lower_sum v (cutoff v.length) le_rfl + have hn := d.sumCapital_nonneg (cutoff v.length) v + linarith + +theorem stake_legal (v : List Bool) : |d.stake v| ≤ d.reserveValue v := by + have h₀ := d.reserve_positive (v ++ [false]) + have h₁ := d.reserve_positive (v ++ [true]) + rw [reserveValue_snoc] at h₀ h₁ + simp only [answerSign_false, answerSign_true] at h₀ h₁ + rw [abs_le] + constructor <;> linarith + +theorem term_le_reserveValue (v : List Bool) (m : ℕ) (hm : m < cutoff v.length) : + (2 : ℚ) ^ m * d.value m v ≤ d.reserveValue v := by + have h := d.reserve_lower_sum v (cutoff v.length) le_rfl + have ht := d.term_le_sumCapital (cutoff v.length) m hm v + linarith + +end SmallMartingales + +end Klr.Splitting diff --git a/LeanPool/KLRandomness/SplittingScheduler.lean b/LeanPool/KLRandomness/SplittingScheduler.lean new file mode 100644 index 0000000000..181e9e8bc9 --- /dev/null +++ b/LeanPool/KLRandomness/SplittingScheduler.lean @@ -0,0 +1,412 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.PartialBettingCapital +public import LeanPool.KLRandomness.EffectiveNormalization +import Mathlib.Tactic.FieldSimp +import Mathlib.Tactic.NormNum +import Mathlib.Tactic.Ring + +/-! +# Scheduling finite-oracle rational bets on the two coordinate halves + +The scheduler reads an initial segment of each half. While the next target +bet is not ready, it reads the next oracle bit with zero wager. A ready bet +reads the next target bit. Thus every query is fresh and eventual readiness +ensures that every target bit is eventually read. The existing partial-program +totalization theorem converts success of this explicit run into failure of KL +randomness. +-/ + +@[expose] public section + +namespace Klr.SplittingScheduler + +open RationalComputability + +/-- Position of the next bit in the parity subsequence on which the program wagers. -/ +def targetPos (side : Bool) (n : ℕ) : ℕ := 2 * n + if side then 1 else 0 +/-- Position of the next bit in the parity subsequence used as an oracle. -/ +def oraclePos (side : Bool) (n : ℕ) : ℕ := 2 * n + if side then 0 else 1 + +/-- `side = false` bets on the even half and uses the odd half as oracle. -/ +def target (side : Bool) (X : Cantor) : Cantor := fun n => X (targetPos side n) +/-- The half of the input used as the oracle. -/ +def oracle (side : Bool) (X : Cantor) : Cantor := fun n => X (oraclePos side n) + +/-- The cached oracle prefix, target prefix and current capital. -/ +abbrev State := List Bool × (List Bool × ℚ) + +/-- The state with empty prefixes and initial capital one. -/ +def initial : State := ([], [], 1) + +/-- Read the next target bit if the readiness test passes, or the next oracle bit otherwise. -/ +def query (side : Bool) (ready : List Bool → ℕ → Bool) (s : State) : ℕ := + bif ready s.1 s.2.1.length then targetPos side s.2.1.length else oraclePos side s.1.length + +/-- The fraction staked on a target query, with no stake on an oracle query. -/ +def requested (ready : List Bool → ℕ → Bool) (bet : List Bool → List Bool → ℚ) + (s : State) : ℚ := + bif ready s.1 s.2.1.length then bet s.1 s.2.1 / s.2.2 else 0 + +/-- The next query position and encoded rational wager. -/ +def action (side : Bool) (ready : List Bool → ℕ → Bool) + (bet : List Bool → List Bool → ℚ) (s : State) : PartialBetting.Action := + (query side ready s, (requested ready bet s).num, (requested ready bet s).den) + +/-- Update the appropriate cached prefix and capital after an answer. -/ +def advance (side : Bool) (ready : List Bool → ℕ → Bool) + (bet : List Bool → List Bool → ℚ) (s : State) (d : Bool) : State := + let capital := s.2.2 * PartialBetting.factor (PartialBetting.fraction (action side ready bet s)) d + bif ready s.1 s.2.1.length then (s.1, s.2.1 ++ [d], capital) + else (s.1 ++ [d], s.2.1, capital) + +theorem advance_capital (side : Bool) (ready : List Bool → ℕ → Bool) + (bet : List Bool → List Bool → ℚ) (s : State) (d : Bool) : + (advance side ready bet s d).2.2 = + s.2.2 * PartialBetting.factor (PartialBetting.fraction (action side ready bet s)) d := by + unfold advance + cases ready s.1 s.2.1.length <;> rfl + +theorem fraction_action (side : Bool) (ready : List Bool → ℕ → Bool) + (bet : List Bool → List Bool → ℚ) (s : State) (h : |requested ready bet s| ≤ 1) : + PartialBetting.fraction (action side ready bet s) = requested ready bet s := by + have hr := PartialBetting.fraction_eq_of_legal (action side ready bet s) + (by simpa only [action, Rat.num_div_den] using h) + simpa only [action, Rat.num_div_den] using hr + +/-- Replay a finite answer string, with a bounded recursion on its length. -/ +def stateAux (side : Bool) (ready : List Bool → ℕ → Bool) + (bet : List Bool → List Bool → ℚ) (v : List Bool) : ℕ → State + | 0 => initial + | n + 1 => advance side ready bet (stateAux side ready bet v n) (v.getD n false) + +/-- Replay the scheduler along the given finite sequence of answers. -/ +def state (side : Bool) (ready : List Bool → ℕ → Bool) + (bet : List Bool → List Bool → ℚ) (v : List Bool) : State := + stateAux side ready bet v v.length + +theorem stateAux_congr (side : Bool) (ready : List Bool → ℕ → Bool) + (bet : List Bool → List Bool → ℚ) (v w : List Bool) (n : ℕ) + (h : ∀ i < n, v.getD i false = w.getD i false) : + stateAux side ready bet v n = stateAux side ready bet w n := by + induction n with + | zero => rfl + | succ n ih => + rw [stateAux, stateAux, ih (fun i hi => h i (by omega)), h n (by omega)] + +@[simp] theorem state_nil (side : Bool) (ready : List Bool → ℕ → Bool) + (bet : List Bool → List Bool → ℚ) : state side ready bet [] = initial := rfl + +theorem state_snoc (side : Bool) (ready : List Bool → ℕ → Bool) + (bet : List Bool → List Bool → ℚ) (v : List Bool) (d : Bool) : + state side ready bet (v ++ [d]) = advance side ready bet (state side ready bet v) d := by + unfold state + rw [List.length_append, List.length_singleton, stateAux] + have h := stateAux_congr side ready bet (v ++ [d]) v v.length (by + intro i hi + simp only [List.getD_eq_getElem?_getD, List.getElem?_append_left hi]) + rw [h] + simp [List.getD_eq_getElem?_getD] + +theorem computable_query (side : Bool) {ready : List Bool → ℕ → Bool} + (hr : Computable₂ ready) : Computable (query side ready) := by + have ho : Computable (fun s : State => s.1.length) := + Computable.list_length.comp Computable.fst + have ht : Computable (fun s : State => s.2.1.length) := + Computable.list_length.comp (Computable.fst.comp Computable.snd) + have hc := hr.comp Computable.fst ht + exact Computable.cond hc + (Primrec.nat_add.to_comp.comp (Primrec.nat_mul.to_comp.comp (Computable.const 2) ht) + (Computable.const (if side then 1 else 0))) + (Primrec.nat_add.to_comp.comp (Primrec.nat_mul.to_comp.comp (Computable.const 2) ho) + (Computable.const (if side then 0 else 1))) + +theorem computable_requested {ready : List Bool → ℕ → Bool} + {bet : List Bool → List Bool → ℚ} (hr : Computable₂ ready) (hb : Computable₂ bet) : + Computable (requested ready bet) := by + have ht : Computable (fun s : State => s.2.1) := Computable.fst.comp Computable.snd + exact Computable.cond (hr.comp Computable.fst (Computable.list_length.comp ht)) + (primrec_rat_div.to_comp.comp (hb.comp Computable.fst ht) + (Computable.snd.comp Computable.snd)) (Computable.const 0) + +theorem computable_action (side : Bool) {ready : List Bool → ℕ → Bool} + {bet : List Bool → List Bool → ℚ} (hr : Computable₂ ready) (hb : Computable₂ bet) : + Computable (action side ready bet) := + (computable_query side hr).pair + ((primrec_rat_num.to_comp.comp (computable_requested hr hb)).pair + (primrec_rat_den.to_comp.comp (computable_requested hr hb))) + +theorem computable_advance (side : Bool) {ready : List Bool → ℕ → Bool} + {bet : List Bool → List Bool → ℚ} (hr : Computable₂ ready) (hb : Computable₂ bet) : + Computable₂ (advance side ready bet) := by + have ho : Computable (fun p : State × Bool => p.1.1) := + Computable.fst.comp Computable.fst + have ht : Computable (fun p : State × Bool => p.1.2.1) := + Computable.fst.comp (Computable.snd.comp Computable.fst) + have hq : Computable (fun p : State × Bool => p.1.2.2) := + Computable.snd.comp (Computable.snd.comp Computable.fst) + have ha : Computable (fun p : State × Bool => action side ready bet p.1) := + (computable_action side hr hb).comp Computable.fst + have hf := PartialBetting.primrec_factor.to_comp.comp + (PartialBetting.primrec_fraction.to_comp.comp ha) Computable.snd + have hcapital := primrec_rat_mul.to_comp.comp hq hf + exact Computable.cond (hr.comp ho (Computable.list_length.comp ht)) + (ho.pair ((Computable.list_concat.comp ht Computable.snd).pair hcapital)) + ((Computable.list_concat.comp ho Computable.snd).pair (ht.pair hcapital)) + +theorem computable_state (side : Bool) {ready : List Bool → ℕ → Bool} + {bet : List Bool → List Bool → ℚ} (hr : Computable₂ ready) (hb : Computable₂ bet) : + Computable (state side ready bet) := by + have hs : Computable₂ (fun v : List Bool => fun p : ℕ × State => + advance side ready bet p.2 (v.getD p.1 false)) := + ((computable_advance side hr hb).comp (Computable.snd.comp Computable.snd) + ((Primrec.list_getD false).to_comp.comp Computable.fst + (Computable.fst.comp Computable.snd))).to₂ + apply (Computable.nat_rec Computable.list_length (Computable.const initial) hs).of_eq + intro v + change (Nat.rec initial (fun n s => advance side ready bet s (v.getD n false)) v.length) = + stateAux side ready bet v v.length + generalize v.length = n + induction n with + | zero => rfl + | succ n ih => simp only [stateAux, ih] + +/-- The exact sequence of source states on the actual input. -/ +def run (side : Bool) (ready : List Bool → ℕ → Bool) + (bet : List Bool → List Bool → ℚ) (X : Cantor) : ℕ → State + | 0 => initial + | n + 1 => advance side ready bet (run side ready bet X n) + (X (query side ready (run side ready bet X n))) + +private theorem inputPrefix_succ (X : Cantor) (n : ℕ) : + ScanRule.inputPrefix X (n + 1) = ScanRule.inputPrefix X n ++ [X n] := by + simp [ScanRule.inputPrefix, List.range_succ] + +theorem run_prefixes (side : Bool) (ready : List Bool → ℕ → Bool) + (bet : List Bool → List Bool → ℚ) (X : Cantor) (n : ℕ) : + (run side ready bet X n).1 = + ScanRule.inputPrefix (oracle side X) (run side ready bet X n).1.length ∧ + (run side ready bet X n).2.1 = + ScanRule.inputPrefix (target side X) (run side ready bet X n).2.1.length := by + induction n with + | zero => exact ⟨rfl, rfl⟩ + | succ n ih => + cases hr : ready (run side ready bet X n).1 (run side ready bet X n).2.1.length + · simp only [run, advance, query, hr, Bool.cond_false] + constructor + · simpa only [List.length_append, List.length_singleton, inputPrefix_succ, oracle] using + congrArg (fun v => v ++ [X (oraclePos side (run side ready bet X n).1.length)]) ih.1 + · exact ih.2 + · simp only [run, advance, query, hr, Bool.cond_true] + constructor + · exact ih.1 + · simpa only [List.length_append, List.length_singleton, inputPrefix_succ, target] using + congrArg (fun v => v ++ [X (targetPos side (run side ready bet X n).2.1.length)]) ih.2 + +theorem oracle_length_mono (side : Bool) (ready : List Bool → ℕ → Bool) + (bet : List Bool → List Bool → ℚ) (X : Cantor) : + Monotone (fun n => (run side ready bet X n).1.length) := by + apply monotone_nat_of_le_succ + intro n + simp only [run, advance] + cases ready (run side ready bet X n).1 (run side ready bet X n).2.1.length <;> simp + +theorem target_length_mono (side : Bool) (ready : List Bool → ℕ → Bool) + (bet : List Bool → List Bool → ℚ) (X : Cantor) : + Monotone (fun n => (run side ready bet X n).2.1.length) := by + apply monotone_nat_of_le_succ + intro n + simp only [run, advance] + cases ready (run side ready bet X n).1 (run side ready bet X n).2.1.length <;> simp + +theorem query_ne_of_lt (side : Bool) (ready : List Bool → ℕ → Bool) + (bet : List Bool → List Bool → ℚ) (X : Cantor) {m n : ℕ} (hmn : m < n) : + query side ready (run side ready bet X m) ≠ query side ready (run side ready bet X n) := by + have ho := oracle_length_mono side ready bet X (show m + 1 ≤ n by omega) + have ht := target_length_mono side ready bet X (show m + 1 ≤ n by omega) + cases hm : ready (run side ready bet X m).1 (run side ready bet X m).2.1.length <;> + cases hn : ready (run side ready bet X n).1 (run side ready bet X n).2.1.length <;> + simp only [run, advance, hm, Bool.cond_false, Bool.cond_true, + List.length_append, List.length_singleton] at ho ht <;> + simp only [query, hm, hn, Bool.cond_false, Bool.cond_true, targetPos, oraclePos] <;> + cases side <;> simp only [Bool.false_eq_true, ite_false, ite_true] at * <;> omega + +theorem query_injective (side : Bool) (ready : List Bool → ℕ → Bool) + (bet : List Bool → List Bool → ℚ) (X : Cantor) : + Function.Injective (fun n => query side ready (run side ready bet X n)) := by + intro m n h + rcases lt_trichotomy m n with hmn | rfl | hnm + · exact False.elim (query_ne_of_lt side ready bet X hmn h) + · rfl + · exact False.elim (query_ne_of_lt side ready bet X hnm h.symm) + +/-- Every finite prefix of the target half is eventually completed. -/ +theorem reaches_target_length (side : Bool) (ready : List Bool → ℕ → Bool) + (bet : List Bool → List Bool → ℚ) (X : Cantor) + (hready : ∀ n, ∃ K, ∀ m, K ≤ m → + ready (ScanRule.inputPrefix (oracle side X) m) n = true) (n : ℕ) : + ∃ t, (run side ready bet X t).2.1.length = n := by + have next (t : ℕ) : ∃ u, (run side ready bet X u).2.1.length = + (run side ready bet X t).2.1.length + 1 := by + let k := (run side ready bet X t).2.1.length + obtain ⟨K, hK⟩ := hready k + have progress : ∀ d t, (run side ready bet X t).2.1.length = k → + K ≤ (run side ready bet X t).1.length + d → + ∃ u, (run side ready bet X u).2.1.length = k + 1 := by + intro d + induction d with + | zero => + intro t ht hbound + have hr : ready (run side ready bet X t).1 (run side ready bet X t).2.1.length = true := by + rw [(run_prefixes side ready bet X t).1, ht] + exact hK _ (by simpa using hbound) + refine ⟨t + 1, ?_⟩ + simp only [run, advance, hr, Bool.cond_true, List.length_append, List.length_singleton] + omega + | succ d ih => + intro t ht hbound + cases hr : ready (run side ready bet X t).1 (run side ready bet X t).2.1.length + · apply ih (t + 1) + · simpa only [run, advance, hr, Bool.cond_false] using ht + · simpa only [run, advance, hr, Bool.cond_false, + List.length_append, List.length_singleton, Nat.add_assoc, + Nat.add_comm 1 d] using hbound + · refine ⟨t + 1, ?_⟩ + simp only [run, advance, hr, Bool.cond_true, List.length_append, List.length_singleton] + omega + exact progress K t rfl (by omega) + induction n with + | zero => exact ⟨0, rfl⟩ + | succ n ih => + obtain ⟨t, ht⟩ := ih + obtain ⟨u, hu⟩ := next t + exact ⟨u, by simpa only [ht] using hu⟩ + +theorem state_answers_eq_run (side : Bool) (ready : List Bool → ℕ → Bool) + (bet : List Bool → List Bool → ℚ) (X : Cantor) (n : ℕ) : + state side ready bet + (ScanRule.inputPrefix (fun i => X (query side ready (run side ready bet X i))) n) = + run side ready bet X n := by + induction n with + | zero => rfl + | succ n ih => rw [inputPrefix_succ, state_snoc, ih]; rfl + +/-- Compile the scheduler and obtain an infinite fresh run on every input. -/ +theorem exists_sourceRun (side : Bool) {ready : List Bool → ℕ → Bool} + {bet : List Bool → List Bool → ℚ} (hr : Computable₂ ready) (hb : Computable₂ bet) + (X : Cantor) : + ∃ c : Nat.Partrec.Code, ∃ r : PartialBetting.SourceRun c X, + (∀ n, r.action n = action side ready bet (run side ready bet X n)) ∧ + ∀ n, PartialBetting.sourceCapital r n = (run side ready bet X n).2.2 := by + have hf : Computable (fun v => action side ready bet (state side ready bet v)) := + (computable_action side hr hb).comp (computable_state side hr hb) + obtain ⟨c, hc⟩ := PartialBetting.exists_partialAction _ hf.partrec + let a : ℕ → PartialBetting.Action := fun n => action side ready bet (run side ready bet X n) + have hanswers (n : ℕ) : + (PartialBetting.sourceAssignment a X n).map Prod.snd = + ScanRule.inputPrefix (fun i => X (query side ready (run side ready bet X i))) n := by + simp [PartialBetting.sourceAssignment, ScanRule.inputPrefix, List.map_map, a, action] + let r : PartialBetting.SourceRun c X := + { action := a + halts := fun n => (PartialBetting.approximate_complete c _ _).mp (by + rw [hanswers, hc] + change a n ∈ Part.some (action side ready bet (state side ready bet + (ScanRule.inputPrefix (fun i => X (query side ready (run side ready bet X i))) n))) + rw [state_answers_eq_run] + exact Part.mem_some _) + fresh := query_injective side ready bet X } + refine ⟨c, r, fun _ => rfl, ?_⟩ + intro n + induction n with + | zero => simp [PartialBetting.sourceCapital, run, initial] + | succ n ih => + change (∏ i ∈ Finset.range (n + 1), PartialBetting.factor + (PartialBetting.fraction (r.action i)) (X (r.action i).1)) = _ + rw [Finset.prod_range_succ] + change PartialBetting.sourceCapital r n * _ = _ + rw [ih] + rw [run, advance_capital] + rfl + +/-- Along the actual input, certified additive stakes reproduce the desired capital exactly. -/ +theorem run_capital_eq (side : Bool) (ready : List Bool → ℕ → Bool) + (bet : List Bool → List Bool → ℚ) (X : Cantor) (Q q : List Bool → ℚ) + (hinit : Q [] = 1) (hpos : ∀ v, 0 < Q v) (hlegal : ∀ v, |q v| ≤ Q v) + (hstep : ∀ v d, Q (v ++ [d]) = Q v + answerSign d * q v) + (hbet : ∀ m n, ready (ScanRule.inputPrefix (oracle side X) m) n = true → + bet (ScanRule.inputPrefix (oracle side X) m) (ScanRule.inputPrefix (target side X) n) = + q (ScanRule.inputPrefix (target side X) n)) (n : ℕ) : + (run side ready bet X n).2.2 = Q (run side ready bet X n).2.1 := by + induction n with + | zero => exact hinit.symm + | succ n ih => + let s := run side ready bet X n + have hO : s.1 = ScanRule.inputPrefix (oracle side X) s.1.length := + (run_prefixes side ready bet X n).1 + have hT : s.2.1 = ScanRule.inputPrefix (target side X) s.2.1.length := + (run_prefixes side ready bet X n).2 + cases hr : ready s.1 s.2.1.length + · have hw : requested ready bet s = 0 := by simp [requested, hr] + have hf : PartialBetting.fraction (action side ready bet s) = 0 := by + rw [fraction_action side ready bet s (by rw [hw]; norm_num), hw] + change (advance side ready bet s (X (query side ready s))).2.2 = + Q (advance side ready bet s (X (query side ready s))).2.1 + simp only [advance, hr, Bool.cond_false, hf, PartialBetting.factor, + mul_zero, add_zero, mul_one] + exact ih + · have hb : bet s.1 s.2.1 = q s.2.1 := by + have hh := hbet s.1.length s.2.1.length (by simpa only [← hO] using hr) + simpa only [← hO, ← hT] using hh + have hqpos := hpos s.2.1 + have hqlegal : |q s.2.1 / Q s.2.1| ≤ 1 := by + rw [abs_div, abs_of_pos hqpos] + exact (div_le_one hqpos).mpr (hlegal s.2.1) + have hw : requested ready bet s = q s.2.1 / Q s.2.1 := by + simp only [requested, hr, Bool.cond_true, hb] + exact congrArg (fun t => q s.2.1 / t) ih + have hf : PartialBetting.fraction (action side ready bet s) = q s.2.1 / Q s.2.1 := by + rw [fraction_action side ready bet s (by rwa [hw]), hw] + change (advance side ready bet s (X (query side ready s))).2.2 = + Q (advance side ready bet s (X (query side ready s))).2.1 + simp only [advance, hr, Bool.cond_true, hf] + rw [hstep] + change s.2.2 * (1 + answerSign (X (query side ready s)) * (q s.2.1 / Q s.2.1)) = _ + rw [ih] + field_simp [ne_of_gt hqpos] + ring + +/-- A computable finite-oracle scheduler for a positive unbounded rational capital +contradicts KL randomness in the repository's existing total-strategy convention. -/ +theorem not_kolmogorovLovelandRandom_of_bets (side : Bool) + {ready : List Bool → ℕ → Bool} {bet : List Bool → List Bool → ℚ} + (hr : Computable₂ ready) (hb : Computable₂ bet) (X : Cantor) (Q q : List Bool → ℚ) + (hinit : Q [] = 1) (hpos : ∀ v, 0 < Q v) (hlegal : ∀ v, |q v| ≤ Q v) + (hstep : ∀ v d, Q (v ++ [d]) = Q v + answerSign d * q v) + (hready : ∀ n, ∃ K, ∀ m, K ≤ m → + ready (ScanRule.inputPrefix (oracle side X) m) n = true) + (hbet : ∀ m n, ready (ScanRule.inputPrefix (oracle side X) m) n = true → + bet (ScanRule.inputPrefix (oracle side X) m) (ScanRule.inputPrefix (target side X) n) = + q (ScanRule.inputPrefix (target side X) n)) + (hunbounded : ∀ bound : ℝ, ∃ n, + bound < (Q (ScanRule.inputPrefix (target side X) n) : ℝ)) : + ¬KolmogorovLovelandRandom X := by + intro hX + obtain ⟨c, r, _, hcapital⟩ := exists_sourceRun side hr hb X + apply PartialBetting.no_partial_rational_success hX r + intro bound + obtain ⟨n, hn⟩ := hunbounded bound + obtain ⟨t, ht⟩ := reaches_target_length side ready bet X hready n + refine ⟨t, ?_⟩ + rw [hcapital, run_capital_eq side ready bet X Q q hinit hpos hlegal hstep hbet, + (run_prefixes side ready bet X t).2, ht] + exact hn + +end Klr.SplittingScheduler diff --git a/LeanPool/KLRandomness/SplittingWitness.lean b/LeanPool/KLRandomness/SplittingWitness.lean new file mode 100644 index 0000000000..4b7706107c --- /dev/null +++ b/LeanPool/KLRandomness/SplittingWitness.lean @@ -0,0 +1,240 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.SplittingClopen +public import LeanPool.KLRandomness.SplittingReserve +import Mathlib.Tactic.Push + +/-! +# Witness times and executable finite bets for the splitting argument + +The mathematical witness times are supplied by a failing ML test. Bounded +search on an oracle prefix recovers any finite batch of those times. The +resulting rational stakes are ordinary computable functions of two finite +words; no oracle-computability framework is assumed. +-/ + +@[expose] public section + +namespace Klr.Splitting + +open RationalComputability SparseSearch +open scoped BigOperators + +/-- First successful bounded simulation within the available oracle prefix. -/ +def firstTime (c : Nat.Partrec.Code) (n : ℕ) (s : List Bool) : ℕ := + (List.range (s.length + 1)).findIdx (fun t => accepts c n t s) + +theorem primrec_firstTime (c : Nat.Partrec.Code) : Primrec₂ (firstTime c) := by + have hproj : Primrec (fun p : (ℕ × List Bool) × ℕ => + ((c, (p.1.1, p.2)), p.1.2)) := + ((Primrec.const c).pair ((Primrec.fst.comp Primrec.fst).pair Primrec.snd)).pair + (Primrec.snd.comp Primrec.fst) + have hp := primrec_accepts.comp hproj + exact (Primrec.list_findIdx + (Primrec.list_range.comp (Primrec.succ.comp (Primrec.list_length.comp Primrec.snd))) + hp.to₂).to₂ + +/-- The full finite batch needed before the next target bet has been found. -/ +def ready (c : Nat.Partrec.Code) (s : List Bool) (n : ℕ) : Bool := + (List.range (SmallMartingales.cutoff n)).all fun m => + accepts c (2 * m + 2) s.length s + +theorem ready_iff (c : Nat.Partrec.Code) (s : List Bool) (n : ℕ) : + ready c s n = true ↔ + ∀ m < SmallMartingales.cutoff n, accepts c (2 * m + 2) s.length s = true := by + simp [ready, List.all_eq_true] + +theorem primrec_ready (c : Nat.Partrec.Code) : Primrec₂ (ready c) := by + have hn : Primrec (fun p : List Bool × ℕ => SmallMartingales.cutoff p.2) := + Primrec.nat_add.comp (Primrec.nat_mul.comp (Primrec.const 2) Primrec.snd) + (Primrec.const 6) + have hs : Primrec (fun p : (List Bool × ℕ) × ℕ => p.1.1) := + Primrec.fst.comp Primrec.fst + have hm : Primrec (fun p : (List Bool × ℕ) × ℕ => 2 * p.2 + 2) := + Primrec.nat_add.comp (Primrec.nat_mul.comp (Primrec.const 2) Primrec.snd) + (Primrec.const 2) + have ha := primrec_accepts.comp + (((Primrec.const c).pair (hm.pair (Primrec.list_length.comp hs))).pair hs) + exact (Primrec.list_all (Primrec.list_range.comp hn) ha.to₂).to₂ + +/-- A prefix length by which the test program detects the input at the given level. -/ +noncomputable def witnessTime (T : MartinLofTest) (A : Cantor) (hA : T.Fails A) + (m : ℕ) : ℕ := by + classical + exact Nat.find ((mem_programOpen_iff T.code (2 * m + 2) A).mp (hA (2 * m + 2))) + +theorem witnessTime_spec (T : MartinLofTest) (A : Cantor) (hA : T.Fails A) (m : ℕ) : + A ∈ event T.code (2 * m + 2) (witnessTime T A hA m) := by + classical + exact Nat.find_spec ((mem_programOpen_iff T.code (2 * m + 2) A).mp (hA (2 * m + 2))) + +theorem witnessTime_min (T : MartinLofTest) (A : Cantor) (hA : T.Fails A) + (m k : ℕ) (hk : k < witnessTime T A hA m) : + A ∉ event T.code (2 * m + 2) k := by + classical + exact Nat.find_min ((mem_programOpen_iff T.code (2 * m + 2) A).mp (hA (2 * m + 2))) hk + +theorem witnessTime_le (T : MartinLofTest) (A : Cantor) (hA : T.Fails A) + (m k : ℕ) (hk : A ∈ event T.code (2 * m + 2) k) : + witnessTime T A hA m ≤ k := by + classical + exact Nat.find_min' ((mem_programOpen_iff T.code (2 * m + 2) A).mp (hA (2 * m + 2))) hk + +theorem firstTime_eq_witnessTime (T : MartinLofTest) (A : Cantor) (hA : T.Fails A) + (m k : ℕ) (hk : A ∈ event T.code (2 * m + 2) k) : + firstTime T.code (2 * m + 2) (ScanRule.inputPrefix A k) = witnessTime T A hA m := by + have hle := witnessTime_le T A hA m k hk + unfold firstTime + apply (List.findIdx_eq (by simpa using Nat.lt_succ_of_le hle)).mpr + constructor + · simpa only [event, Set.mem_ofPred_eq, List.getElem_range, accepts_prefix T.code (2 * m + 2) + (witnessTime T A hA m) k hle A] using witnessTime_spec T A hA m + · intro j hj + apply Bool.eq_false_iff.mpr + intro ha + have hjk : j ≤ k := (Nat.le_of_lt hj).trans hle + have he : A ∈ event T.code (2 * m + 2) j := by + simpa only [event, Set.mem_ofPred_eq, List.getElem_range, + accepts_prefix T.code (2 * m + 2) j k hjk A] using ha + exact witnessTime_min T A hA m j hj he + +theorem eventually_ready (T : MartinLofTest) (A : Cantor) (hA : T.Fails A) (n : ℕ) : + ∃ K, ∀ k ≥ K, ready T.code (ScanRule.inputPrefix A k) n = true := by + classical + let K := (Finset.range (SmallMartingales.cutoff n)).sup (witnessTime T A hA) + refine ⟨K, fun k hk => (ready_iff _ _ _).mpr ?_⟩ + intro m hm + have hmK : witnessTime T A hA m ≤ K := + Finset.le_sup (f := witnessTime T A hA) (Finset.mem_range.mpr hm) + have he := event_mono T.code (2 * m + 2) (hmK.trans hk) + (witnessTime_spec T A hA m) + simpa only [event, Set.mem_ofPred_eq, ScanRule.length_inputPrefix] using he + +/-- The fixed finite-event martingales, using witness times from the oracle half. -/ +def family (T : MartinLofTest) (f : ℕ → ℕ) : SmallMartingales where + value m v := clopenCapital T.code (2 * m + 2) (f m) v + nonneg m v := clopenCapital_nonneg T.code (2 * m + 2) (f m) v + fair m v := clopenCapital_fair T.code (2 * m + 2) (f m) v + initial_le m := clopenCapital_initial_le T (2 * m + 2) (f m) + +/-- A finite sum computed from an available oracle prefix. -/ +def knownCapital (oracle target : Nat.Partrec.Code) (s : List Bool) (K : ℕ) + (v : List Bool) : ℚ := + ((List.range K).map fun m => (2 : ℚ) ^ m * + clopenCapital target (2 * m + 2) (firstTime oracle (2 * m + 2) s) v).sum + +/-- The next signed stake computed from the bounded clopen martingales. -/ +def bet (oracle target : Nat.Partrec.Code) (s v : List Bool) : ℚ := + (knownCapital oracle target s (SmallMartingales.cutoff v.length) (v ++ [true]) - + knownCapital oracle target s (SmallMartingales.cutoff v.length) (v ++ [false])) / 2 + +theorem computable_knownCapital (oracle target : Nat.Partrec.Code) : + Computable (fun p : List Bool × (ℕ × List Bool) => + knownCapital oracle target p.1 p.2.1 p.2.2) := by + let α := List Bool × (ℕ × List Bool) + have hs : Computable (fun p : α × ℕ => p.1.1) := + Computable.fst.comp Computable.fst + have hv : Computable (fun p : α × ℕ => p.1.2.2) := + Computable.snd.comp (Computable.snd.comp Computable.fst) + have hl : Computable (fun p : α × ℕ => 2 * p.2 + 2) := + Primrec.nat_add.to_comp.comp (Primrec.nat_mul.to_comp.comp (Computable.const 2) + Computable.snd) (Computable.const 2) + have ht := (primrec_firstTime oracle).to_comp.comp hl hs + have hc := computable_clopenCapital.comp + (((Computable.const target).pair (hl.pair ht)).pair hv) + have hw : Computable (fun p : α × ℕ => (2 : ℚ) ^ p.2) := by + apply (primrec_rat_natCast.to_comp.comp + (Computable.list_length.comp (computable_words.comp Computable.snd))).of_eq + intro p + simp only [PoolAdvice.length_words, Nat.cast_pow, Nat.cast_ofNat] + exact PoolAdvice.computable_list_sum + (Primrec.list_range.to_comp.comp (Computable.fst.comp Computable.snd)) + (primrec_rat_mul.to_comp.comp hw hc).to₂ + +theorem computable_bet (oracle target : Nat.Partrec.Code) : Computable₂ (bet oracle target) := by + have hn : Computable (fun p : List Bool × List Bool => SmallMartingales.cutoff p.2.length) := + Primrec.nat_add.to_comp.comp + (Primrec.nat_mul.to_comp.comp (Computable.const 2) + (Computable.list_length.comp Computable.snd)) (Computable.const 6) + have hc (b : Bool) : Computable (fun p : List Bool × List Bool => + knownCapital oracle target p.1 (SmallMartingales.cutoff p.2.length) (p.2 ++ [b])) := by + have hproj : Computable (fun p : List Bool × List Bool => + (p.1, (SmallMartingales.cutoff p.2.length, p.2 ++ [b]))) := + Computable.fst.pair (hn.pair + (Primrec.list_concat.to_comp.comp Computable.snd (Computable.const b))) + have hh := (computable_knownCapital oracle target).comp hproj + exact hh + exact (primrec_rat_div.to_comp.comp + (primrec_rat_sub.to_comp.comp (hc true) (hc false)) (Computable.const 2)).to₂ + +theorem knownCapital_eq (O T : MartinLofTest) (A : Cantor) (hA : O.Fails A) + (k K : ℕ) (hk : ∀ m < K, A ∈ event O.code (2 * m + 2) k) (v : List Bool) : + knownCapital O.code T.code (ScanRule.inputPrefix A k) K v = + (family T (witnessTime O A hA)).sumCapital K v := by + unfold knownCapital SmallMartingales.sumCapital + rw [← List.sum_toFinset _ (List.nodup_range (n := K))] + simp only [List.toFinset_range] + apply Finset.sum_congr rfl + intro m hm + rw [firstTime_eq_witnessTime O A hA m k (hk m (Finset.mem_range.mp hm))] + rfl + +theorem bet_correct (O T : MartinLofTest) (A : Cantor) (hA : O.Fails A) + (k : ℕ) (v : List Bool) + (hready : ready O.code (ScanRule.inputPrefix A k) v.length = true) : + bet O.code T.code (ScanRule.inputPrefix A k) v = + (family T (witnessTime O A hA)).stake v := by + have hk : ∀ m < SmallMartingales.cutoff v.length, A ∈ event O.code (2 * m + 2) k := by + simpa only [event, Set.mem_ofPred_eq, ScanRule.length_inputPrefix] using + (ready_iff _ _ _).mp hready + unfold bet SmallMartingales.stake + rw [knownCapital_eq O T A hA k _ hk, knownCapital_eq O T A hA k _ hk] + +theorem witness_comparison (f g : ℕ → ℕ) : + (∀ N, ∃ m ≥ N, f m ≤ g m) ∨ (∀ N, ∃ m ≥ N, g m ≤ f m) := by + classical + by_cases h : ∀ N, ∃ m ≥ N, f m ≤ g m + · exact Or.inl h + · right + push Not at h + obtain ⟨N, hN⟩ := h + intro M + refine ⟨max M N, Nat.le_max_left _ _, ?_⟩ + exact (hN _ (Nat.le_max_right _ _)).le + +theorem reserve_unbounded (O T : MartinLofTest) (A B : Cantor) + (hA : O.Fails A) (hB : T.Fails B) + (hcomp : ∀ N, ∃ m ≥ N, witnessTime T B hB m ≤ witnessTime O A hA m) : + ∀ bound : ℝ, ∃ n, + bound < ((family T (witnessTime O A hA)).reserveValue (ScanRule.inputPrefix B n) : ℝ) := by + intro bound + obtain ⟨N, hN⟩ := exists_nat_gt bound + obtain ⟨m, hmN, hm⟩ := hcomp N + let n := max (witnessTime O A hA m) m + have hn : witnessTime O A hA m ≤ n := Nat.le_max_left _ _ + have hmn : m < SmallMartingales.cutoff (ScanRule.inputPrefix B n).length := by + simp only [ScanRule.length_inputPrefix, SmallMartingales.cutoff] + have := Nat.le_max_right (witnessTime O A hA m) m + omega + have he := event_mono T.code (2 * m + 2) hm (witnessTime_spec T B hB m) + have hv : (family T (witnessTime O A hA)).value m (ScanRule.inputPrefix B n) = 1 := + clopenCapital_eq_one T.code (2 * m + 2) (witnessTime O A hA m) B he hn + have hq := (family T (witnessTime O A hA)).term_le_reserveValue + (ScanRule.inputPrefix B n) m hmn + rw [hv, mul_one] at hq + have hqr : (2 : ℝ) ^ m ≤ + ((family T (witnessTime O A hA)).reserveValue (ScanRule.inputPrefix B n) : ℝ) := by + exact_mod_cast hq + have hpow : (m : ℝ) < (2 : ℝ) ^ m := by exact_mod_cast m.lt_two_pow_self + have hNm : (N : ℝ) ≤ m := by exact_mod_cast hmN + exact ⟨n, hN.trans_le (hNm.trans (hpow.le.trans hqr))⟩ + +end Klr.Splitting diff --git a/LeanPool/KLRandomness/StageCandidate.lean b/LeanPool/KLRandomness/StageCandidate.lean new file mode 100644 index 0000000000..4eb3efa131 --- /dev/null +++ b/LeanPool/KLRandomness/StageCandidate.lean @@ -0,0 +1,148 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.SparseListWeights +public import LeanPool.KLRandomness.NoDrop + +/-! +# Sparse-list entries as affine blocks on a concrete pool + +The finite search produces Boolean matrices on `Fin M`. This file embeds +their selected columns into natural-number coordinates through an injective +pool enumeration. The syndrome is left free: changing it does not change +any of the rank calculations. +-/ + +@[expose] public section + +noncomputable section + +namespace Klr.StageCandidate + +open SparseListSearch SparseListWeights SparseSearch AffineCode FiniteMeasure +open RandomMatrix AffineObservation +open scoped BigOperators + +variable {M m r : ℕ} + +/-- A coded column, read at the dimensions guaranteed by `GoodEntry`. -/ +def columns (a : Entry) (M r : ℕ) (j : Fin M) (i : Fin r) : ZMod 2 := + boolEquivF2 (entry (rows a.2) i.val j.val) + +theorem columns_zero_off_support {a : Entry} (ha : GoodEntry M m r a) + {j : Fin M} (hj : j ∉ support M a) : columns a M r j = 0 := by + have hm : a.1.getD j.val false = false := by + simpa [support, SparseListCode.mem_maskSet] using hj + funext i + simp only [columns, Pi.zero_apply, ha.2.2.2.2.2 i.val i.isLt j.val j.isLt hm] + rfl + +theorem restricted_columns_surjective {a : Entry} (ha : GoodEntry M m r a) : + Function.Surjective (restrictedMap (columns a M r) (support M a) (K := ZMod 2)) := by + have hw := ha.2.2.1 + have hr := ha.2.2.2.1 + cases hw + cases hr + exact ha.restricted_fullRank + +theorem masked_columns_surjective {a : Entry} (ha : GoodEntry M m r a) + (d : List Bool) (hd : maskedFullRank a.2 d = true) : + Function.Surjective + (restrictedMap (columns a M r) (SparseListCode.maskSet M d) (K := ZMod 2)) := by + have hw := ha.2.2.1 + have hr := ha.2.2.2.1 + cases hw + cases hr + exact (maskedFullRank_eq_true a.2 d).mp hd + +/-- The executable rank checker at the dimensions supplied by `GoodEntry`. -/ +theorem maskedFullRank_iff_columns_surjective {a : Entry} (ha : GoodEntry M m r a) + (d : List Bool) : + maskedFullRank a.2 d = true ↔ Function.Surjective + (restrictedMap (columns a M r) (SparseListCode.maskSet M d) (K := ZMod 2)) := by + have hw := ha.2.2.1 + have hr := ha.2.2.2.1 + cases hw + cases hr + exact maskedFullRank_eq_true a.2 d + +/-- The selected natural-number positions of a concrete pool. -/ +def positions (e : Fin M → ℕ) (a : Entry) : Finset ℕ := (support M a).image e + +/-- The mask coordinates and their actual natural-number positions are equivalent. -/ +def positionEquiv (e : Fin M → ℕ) (he : Function.Injective e) (a : Entry) : + support M a ≃ positions e a := + Equiv.ofBijective + (fun j => ⟨e j.val, Finset.mem_image_of_mem e j.property⟩) + ⟨fun j k h => Subtype.ext (he (congrArg Subtype.val h)), by + rintro ⟨p, hp⟩ + obtain ⟨j, hj, rfl⟩ := Finset.mem_image.mp hp + exact ⟨⟨j, hj⟩, rfl⟩⟩ + +@[simp] theorem positionEquiv_val (e : Fin M → ℕ) (he : Function.Injective e) + (a : Entry) (j : support M a) : (positionEquiv e he a j).val = e j.val := rfl + +/-- Pull an assignment on actual positions back to the selected mask coordinates. -/ +def pullback (e : Fin M → ℕ) (he : Function.Injective e) (a : Entry) : + (positions e a → ZMod 2) →ₗ[ZMod 2] (support M a → ZMod 2) where + toFun x j := x (positionEquiv e he a j) + map_add' _ _ := rfl + map_smul' _ _ := rfl + +theorem pullback_surjective (e : Fin M → ℕ) (he : Function.Injective e) (a : Entry) : + Function.Surjective (pullback e he a) := by + intro x + refine ⟨fun p => x ((positionEquiv e he a).symm p), ?_⟩ + ext j + simp [pullback] + +/-- The affine block represented by a checked sparse-list entry, on the given pool. -/ +def block (e : Fin M → ℕ) (he : Function.Injective e) (a : Entry) + (ha : GoodEntry M m r a) (y : Fin r → ZMod 2) : AffineBlock where + support := positions e a + rank := r + matrix := (restrictedMap (columns a M r) (support M a)).comp (pullback e he a) + fullRank := (restricted_columns_surjective ha).comp (pullback_surjective e he a) + syndrome := y + +@[simp] theorem block_support (e : Fin M → ℕ) (he : Function.Injective e) + (a : Entry) (ha : GoodEntry M m r a) (y : Fin r → ZMod 2) : + (block e he a ha y).support = (support M a).image e := rfl + +@[simp] theorem block_rank (e : Fin M → ℕ) (he : Function.Injective e) + (a : Entry) (ha : GoodEntry M m r a) (y : Fin r → ZMod 2) : + (block e he a ha y).rank = r := rfl + +theorem block_support_card (e : Fin M → ℕ) (he : Function.Injective e) + (a : Entry) (ha : GoodEntry M m r a) (y : Fin r → ZMod 2) : + (block e he a ha y).support.card = m := by + rw [block_support, Finset.card_image_of_injective _ he] + exact (SparseListCode.card_maskSet M a.1 ha.1).trans ha.2.1 + +theorem block_support_subset (e : Fin M → ℕ) (he : Function.Injective e) + (a : Entry) (ha : GoodEntry M m r a) (y : Fin r → ZMod 2) : + (block e he a ha y).support ⊆ Finset.univ.image e := + Finset.image_subset_image (Finset.subset_univ _) + +theorem block_matrix_single (e : Fin M → ℕ) (he : Function.Injective e) + (a : Entry) (ha : GoodEntry M m r a) (y : Fin r → ZMod 2) + (j : support M a) : + (block e he a ha y).matrix (Pi.single (positionEquiv e he a j) 1) = + columns a M r j.val := by + classical + have hp : pullback e he a (Pi.single (positionEquiv e he a j) 1) = Pi.single j 1 := by + ext k + simp [pullback, Pi.single_apply, (positionEquiv e he a).injective.eq_iff] + change restrictedMap (columns a M r) (support M a) + (pullback e he a (Pi.single (positionEquiv e he a j) 1)) = _ + rw [hp] + exact columnMap_single _ j + +end Klr.StageCandidate diff --git a/LeanPool/KLRandomness/StageCandidateBridge.lean b/LeanPool/KLRandomness/StageCandidateBridge.lean new file mode 100644 index 0000000000..3865f8026e --- /dev/null +++ b/LeanPool/KLRandomness/StageCandidateBridge.lean @@ -0,0 +1,203 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.StagePreHorizon +public import LeanPool.KLRandomness.HorizonAvoidance +public import LeanPool.KLRandomness.LateDropBound + +/-! +# Concrete candidate coordinates and stage cutoffs + +The pre-horizon theorem labels the pool by `Fin (r^8)`. The executable +finite statistics use the pool list's own `Fin G.length` enumeration. These +representations yield exactly the same affine block, including its matrix. + +One explicit cutoff avoids the old block supports and every query on every +branch through every earlier protected horizon. A good pool beyond that +cutoff therefore supplies both disjointness and all future-preservation +conditions needed when the selected candidate is appended to the stages. +-/ + +@[expose] public section + +namespace Klr.StageCandidateBridge + +open MeasureTheory SparseListSearch StageChoice StagePreHorizon + +/-- Transporting the pool-length equality does not change the embedded +affine block. The complete matrix agrees, not only its support or event. -/ +theorem block_poolLabel_eq {M m r : ℕ} (G : List ℕ) + (hGM : G.length = M) (hG : G.Nodup) (a : Entry) + (ha : GoodEntry M m r a) (ha' : GoodEntry G.length m r a) + (y : Fin r → ZMod 2) : + StageCandidate.block (poolLabel G hGM) (poolLabel_injective G hGM hG) a ha y = + StageCandidate.block G.get hG.injective_get a ha' y := by + subst M + rfl + +/-- The selected executable entry is good at the actual pool-list length. -/ +theorem candidate_goodEntry {τ θ : ℚ} {r : ℕ} {G : List ℕ} {L : CodeList} + (hGM : G.length = SparseParameters.blockSize r) + (hL : L ∈ SparseListConstruction.construct τ θ r) (q : Fin L.length) : + GoodEntry G.length (SparseParameters.supportSize r) r (L.get q) := by + rw [hGM] + exact (SparseListConstruction.construct_spec hL).2.1 _ (List.get_mem L q) + +/-- The candidate supplied by the analytic selection theorem is exactly +the block used by the finite code and rank interpreters. -/ +theorem candidate_eq_block {τ θ : ℚ} {r : ℕ} {G : List ℕ} {L : CodeList} + (hGM : G.length = SparseParameters.blockSize r) (hG : G.Nodup) + (hL : L ∈ SparseListConstruction.construct τ θ r) (q : Fin L.length) + (ha : GoodEntry G.length (SparseParameters.supportSize r) r (L.get q)) + (y : Fin r → ZMod 2) : + candidate hGM hG hL q y = StageCandidate.block G.get hG.injective_get (L.get q) ha y := + block_poolLabel_eq G hGM hG (L.get q) + ((SparseListConstruction.construct_spec hL).2.1 _ (List.get_mem L q)) ha y + +/-- The direct finite-statistics block uses only positions in the actual pool. -/ +theorem block_support_subset_pool {m r : ℕ} (G : List ℕ) (hG : G.Nodup) + (a : Entry) (ha : GoodEntry G.length m r a) (y : Fin r → ZMod 2) : + (StageCandidate.block G.get hG.injective_get a ha y).support ⊆ G.toFinset := by + intro p hp + obtain ⟨j, _, rfl⟩ := Finset.mem_image.mp hp + exact List.mem_toFinset.mpr (List.get_mem G j) + +/-- The selected block inherits the pool program's lower position cutoff. -/ +theorem candidate_support_ge_of_goodPool {τ θ : ℚ} {r ℓ z : ℕ} + {G : List ℕ} {L : CodeList} {π : ℕ → ScanRule} {H : ℕ → Set Cantor} {η : ℝ} + (hG : PoolConstruction.GoodPool π H ℓ η z τ (SparseParameters.blockSize r) G) + (hL : L ∈ SparseListConstruction.construct τ θ r) (q : Fin L.length) + (y : Fin r → ZMod 2) : + ∀ p ∈ (candidate hG.1 hG.2.1 hL q y).support, z ≤ p := by + intro p hp + exact hG.2.2.1 p (List.mem_toFinset.mp (candidate_support_subset hG.1 hG.2.1 hL q y hp)) + +/-- A pool beyond `z + 1` gives a strict cutoff, when that convention is convenient. -/ +theorem candidate_support_gt_of_goodPool {τ θ : ℚ} {r ℓ z : ℕ} + {G : List ℕ} {L : CodeList} {π : ℕ → ScanRule} {H : ℕ → Set Cantor} {η : ℝ} + (hG : PoolConstruction.GoodPool π H ℓ η (z + 1) τ (SparseParameters.blockSize r) G) + (hL : L ∈ SparseListConstruction.construct τ θ r) (q : Fin L.length) + (y : Fin r → ZMod 2) : + ∀ p ∈ (candidate hG.1 hG.2.1 hL q y).support, z < p := + candidate_support_ge_of_goodPool hG hL q y + +/-- The input-space low-drop event has the exact form required by the +stage estimates and their later-stage comparison theorem. -/ +theorem lowDropInput_eq (s : BettingStrategy) (H : Set Cantor) (C : AffineBlock) : + lowDropInput s H C = + s.normalize.scan.observationMap ⁻¹' Hᶜ ∩ LateDropBound.hasDrop C s.normalize.scan := by + simp only [lowDropInput, Set.preimage_inter, Set.preimage_compl, + NoDrop.observationMap_preimage_noDropTranscripts, LateDropBound.hasDrop] + +/-- Full positive unread rank on the high part forces a missed coordinate +of every pool containing the support. This inclusion is pointwise. -/ +theorem high_noDrop_subset_highMissInput (s : BettingStrategy) (H : Set Cantor) + (G : List ℕ) (C : AffineBlock) (hCG : C.support ⊆ G.toFinset) (hr : 0 < C.rank) : + s.normalize.scan.observationMap ⁻¹' H ∩ NoDrop.noDropEvent C s.normalize.scan ⊆ + highMissInput s H G := by + intro X hX + have ht : s.normalize.scan.observationMap X ∈ NoDrop.noDropTranscripts C s.normalize.scan := by + change X ∈ s.normalize.scan.observationMap ⁻¹' NoDrop.noDropTranscripts C s.normalize.scan + rw [NoDrop.observationMap_preimage_noDropTranscripts] + exact hX.2 + have hm := StageRank.noDropTranscripts_subset_missed C s.normalize.scan G.toFinset hCG hr ht + obtain ⟨b, hb, hnb⟩ := + (PoolQuery.missedCount_pos_iff s.normalize.scan G.toFinset _).mp hm + exact ⟨hX.1, b, List.mem_toFinset.mp hb, hnb⟩ + +theorem measure_high_noDrop_le_highMissInput (μ : Measure Cantor) + (s : BettingStrategy) (H : Set Cantor) (G : List ℕ) (C : AffineBlock) + (hCG : C.support ⊆ G.toFinset) (hr : 0 < C.rank) : + μ (s.normalize.scan.observationMap ⁻¹' H ∩ NoDrop.noDropEvent C s.normalize.scan) ≤ + μ (highMissInput s H G) := + measure_mono (high_noDrop_subset_highMissInput s H G C hCG hr) + +theorem measureReal_high_noDrop_le_highMissInput (μ : Measure Cantor) [IsFiniteMeasure μ] + (s : BettingStrategy) (H : Set Cantor) (G : List ℕ) (C : AffineBlock) + (hCG : C.support ⊆ G.toFinset) (hr : 0 < C.rank) : + μ.real (s.normalize.scan.observationMap ⁻¹' H ∩ NoDrop.noDropEvent C s.normalize.scan) ≤ + μ.real (highMissInput s H G) := + measureReal_mono (high_noDrop_subset_highMissInput s H G C hCG hr) + +/-- Old supports and every earlier protected all-branch query set. Stage +`j` protected scans `0, ..., j` through its horizon `V j`. -/ +def stagePositions (B : ℕ → AffineBlock) (π : ℕ → ScanRule) (V : ℕ → ℕ) + (n : ℕ) : Finset ℕ := + PrefixStage.prefixSupport B n ∪ (Finset.range n).biUnion + (fun j => HorizonAvoidance.familyPositions (fun i : Fin (j + 1) => π i) (fun _ => V j)) + +/-- A strict upper bound for everything that the next support must avoid. -/ +def stageCutoff (B : ℕ → AffineBlock) (π : ℕ → ScanRule) (V : ℕ → ℕ) (n : ℕ) : ℕ := + (stagePositions B π V n).sup id + 1 + +theorem lt_stageCutoff_of_mem (B : ℕ → AffineBlock) (π : ℕ → ScanRule) + (V : ℕ → ℕ) (n : ℕ) {p : ℕ} (hp : p ∈ stagePositions B π V n) : + p < stageCutoff B π V n := Nat.lt_succ_of_le (Finset.le_sup (f := id) hp) + +theorem old_support_subset_stagePositions (B : ℕ → AffineBlock) (π : ℕ → ScanRule) + (V : ℕ → ℕ) (n j : ℕ) (hj : j < n) : + (B j).support ⊆ stagePositions B π V n := by + intro p hp + exact Finset.mem_union_left _ ((PrefixStage.mem_prefixSupport B n p).mpr ⟨j, hj, hp⟩) + +theorem queryPositions_subset_stagePositions (B : ℕ → AffineBlock) (π : ℕ → ScanRule) + (V : ℕ → ℕ) (n j : ℕ) (hj : j < n) (i : ℕ) (hi : i ≤ j) : + HorizonAvoidance.queryPositions (π i) (V j) ⊆ stagePositions B π V n := by + intro p hp + apply Finset.mem_union_right + apply Finset.mem_biUnion.mpr + refine ⟨j, Finset.mem_range.mpr hj, ?_⟩ + exact HorizonAvoidance.queryPositions_subset_familyPositions + (fun i : Fin (j + 1) => π i) (fun _ => V j) ⟨i, Nat.lt_succ_of_le hi⟩ hp + +theorem old_support_lt_stageCutoff (B : ℕ → AffineBlock) (π : ℕ → ScanRule) + (V : ℕ → ℕ) (n j : ℕ) (hj : j < n) (p : ℕ) (hp : p ∈ (B j).support) : + p < stageCutoff B π V n := + lt_stageCutoff_of_mem B π V n (old_support_subset_stagePositions B π V n j hj hp) + +theorem query_lt_stageCutoff (B : ℕ → AffineBlock) (π : ℕ → ScanRule) + (V : ℕ → ℕ) (n j : ℕ) (hj : j < n) (i : ℕ) (hi : i ≤ j) + (v : List Bool) (hv : v.length < V j) : (π i).query v < stageCutoff B π V n := + lt_stageCutoff_of_mem B π V n (queryPositions_subset_stagePositions B π V n j hj i hi + (HorizonAvoidance.query_mem_queryPositions (π i) (V j) v hv)) + +/-- The explicit cutoff simultaneously guarantees disjointness from every +old block and full unread rank through every old protected horizon. -/ +theorem consequences_of_stageCutoff_le (B : ℕ → AffineBlock) (π : ℕ → ScanRule) + (V : ℕ → ℕ) (n : ℕ) (C : AffineBlock) + (hC : ∀ p ∈ C.support, stageCutoff B π V n ≤ p) : + (∀ j < n, Disjoint (B j).support C.support) ∧ + ∀ j < n, ∀ i ≤ j, ∀ v : List Bool, v.length ≤ V j → C.UnreadFullRank (π i) v := by + have hd : Disjoint (stagePositions B π V n) C.support := by + apply Finset.disjoint_left.mpr + intro p hp hpC + exact (not_lt_of_ge (hC p hpC)) (lt_stageCutoff_of_mem B π V n hp) + constructor + · intro j hj + exact hd.mono_left (old_support_subset_stagePositions B π V n j hj) + · intro j hj i hi v hv + exact HorizonAvoidance.unreadFullRank_of_disjoint C (π i) (V j) + (hd.mono_left (queryPositions_subset_stagePositions B π V n j hj i hi)) v hv + +/-- A good pool above the concrete stage cutoff discharges all support +separation and horizon-preservation requirements for the selected candidate. -/ +theorem candidate_preserves_prior_horizons {τ θ : ℚ} {r ℓ z : ℕ} + {G : List ℕ} {L : CodeList} {π : ℕ → ScanRule} {H : ℕ → Set Cantor} {η : ℝ} + (hG : PoolConstruction.GoodPool π H ℓ η z τ (SparseParameters.blockSize r) G) + (hL : L ∈ SparseListConstruction.construct τ θ r) (q : Fin L.length) + (y : Fin r → ZMod 2) (B : ℕ → AffineBlock) (V : ℕ → ℕ) (n : ℕ) + (hz : stageCutoff B π V n ≤ z) : + (∀ j < n, Disjoint (B j).support (candidate hG.1 hG.2.1 hL q y).support) ∧ + ∀ j < n, ∀ i ≤ j, ∀ v : List Bool, v.length ≤ V j → + (candidate hG.1 hG.2.1 hL q y).UnreadFullRank (π i) v := + consequences_of_stageCutoff_le B π V n _ + (fun p hp => hz.trans (candidate_support_ge_of_goodPool hG hL q y p hp)) + +end Klr.StageCandidateBridge diff --git a/LeanPool/KLRandomness/StageCandidateCode.lean b/LeanPool/KLRandomness/StageCandidateCode.lean new file mode 100644 index 0000000000..1454049eea --- /dev/null +++ b/LeanPool/KLRandomness/StageCandidateCode.lean @@ -0,0 +1,173 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.StageCandidate +public import LeanPool.KLRandomness.StageCodeSearch + +/-! +# Computable affine output for a candidate on an actual pool + +The candidate matrix is indexed by pool positions, whereas the output code +is indexed by input coordinates. Its finite truth table is computed by +pulling an input word back along the finite pool list. Certified code search +then performs the coordinate change and supplies a right inverse, with no +matrix or certificate added to the description as advice. +-/ + +@[expose] public section + +namespace Klr.StageCandidateCode + +open AffineCode SparseSearch SparseListSearch FiniteMeasure RandomMatrix +open StageCandidate +open scoped BigOperators + +/-- Replace the candidate's syndrome while leaving its matrix unchanged. -/ +def withSyndrome (c : Data) (y : List Bool) : Data := + (c.1, (rows c, (y, certificate c))) + +@[simp] theorem width_withSyndrome (c : Data) (y : List Bool) : + width (withSyndrome c y) = width c := rfl + +@[simp] theorem rank_withSyndrome (c : Data) (y : List Bool) : + rank (withSyndrome c y) = rank c := rfl + +@[simp] theorem matrix_withSyndrome (c : Data) (y : List Bool) : + matrix (withSyndrome c y) = matrix c := rfl + +theorem computable_withSyndrome : Computable₂ withSyndrome := by + exact ((Computable.fst.comp Computable.fst).pair + ((computable_rows.comp Computable.fst).pair + (Computable.snd.pair (computable_certificate.comp Computable.fst)))).to₂ + +/-- Read a finite input word at the actual pool positions. -/ +def poolWord (G : List ℕ) (s : List Bool) : List Bool := + G.map (fun k => s.getD k false) + +theorem computable_poolWord : Computable₂ poolWord := by + exact (Primrec.list_map Primrec.fst + ((Primrec.list_getD false).comp (Primrec.snd.comp Primrec.fst) Primrec.snd).to₂).to_comp + +theorem getD_poolWord (G : List ℕ) (s : List Bool) (j : Fin G.length) : + (poolWord G s).getD j.val false = s.getD (G.get j) false := by + simp [poolWord, List.getD_eq_getElem?_getD, j.isLt] + +/-- A computable coordinate bound for the entire concrete pool. -/ +def bound (G : List ℕ) : ℕ := G.sum + 1 + +theorem computable_bound : Computable bound := + Primrec.succ.to_comp.comp (Primrec.list_sum Primrec.id).to_comp + +theorem get_lt_bound (G : List ℕ) (j : Fin G.length) : G.get j < bound G := + Nat.lt_succ_of_le (List.le_sum_of_mem (List.get_mem G j)) + +/-- The truth table for the new affine constraint at actual input positions. -/ +def table (G : List ℕ) (c : Data) (y s : List Bool) : Bool := + accepts (withSyndrome c y) (poolWord G s) + +theorem computable_table : Computable + (fun p : ((List ℕ × Data) × List Bool) × List Bool => table p.1.1.1 p.1.1.2 p.1.2 p.2) := by + have hG : Computable (fun p : ((List ℕ × Data) × List Bool) × List Bool => p.1.1.1) := + Computable.fst.comp (Computable.fst.comp Computable.fst) + have hc : Computable (fun p : ((List ℕ × Data) × List Bool) × List Bool => p.1.1.2) := + Computable.snd.comp (Computable.fst.comp Computable.fst) + have hy : Computable (fun p : ((List ℕ × Data) × List Bool) × List Bool => p.1.2) := + Computable.snd.comp Computable.fst + exact computable_accepts.comp (computable_withSyndrome.comp hc hy) + (computable_poolWord.comp hG Computable.snd) + +theorem restrictedMap_eq_columnMap_of_zero {M r : ℕ} + (C : Fin M → Fin r → ZMod 2) (T : Finset (Fin M)) + (hz : ∀ j ∉ T, C j = 0) (x : Fin M → ZMod 2) : + restrictedMap C T (fun j => x j.val) = columnMap C x := by + classical + change (∑ j : T, x j.val • C j.val) = ∑ j, x j • C j + rw [Finset.sum_coe_sort T (fun j => x j • C j)] + exact Finset.sum_subset (Finset.subset_univ _) fun j _ hj => by rw [hz j hj, smul_zero] + +/-- The embedded block computes the original candidate equations on pool bits. -/ +theorem block_matrix_coordinates (G : List ℕ) (hG : G.Nodup) + {m r : ℕ} (a : Entry) (ha : GoodEntry G.length m r a) + (y : Fin r → ZMod 2) (X : Cantor) : + (block G.get hG.injective_get a ha y).matrix + (coordinateValues (fun i => i.val) X) = + columnMap (columns a G.length r) (fun j => boolEquivF2 (X (G.get j))) := by + change restrictedMap (columns a G.length r) (SparseListWeights.support G.length a) + (fun j => boolEquivF2 (X (G.get j.val))) = _ + exact restrictedMap_eq_columnMap_of_zero _ _ (fun j hj => columns_zero_off_support ha hj) + (fun j => boolEquivF2 (X (G.get j))) + +/-- The executable truth table describes the actual embedded affine block. +The input depth may be enlarged to cover old equations and adaptive queries. -/ +theorem table_inputPrefix (G : List ℕ) (hG : G.Nodup) + {m r : ℕ} (a : Entry) (ha : GoodEntry G.length m r a) + (y : List Bool) (n : ℕ) (hn : bound G ≤ n) (X : Cantor) : + table G a.2 y (ScanRule.inputPrefix X n) = true ↔ + X ∈ (block G.get hG.injective_get a ha (wordVector r y)).event := by + have hw := ha.2.2.1 + have hr := ha.2.2.2.1 + rw [table, accepts_eq_true] + have hlen : width (withSyndrome a.2 y) ≤ (poolWord G (ScanRule.inputPrefix X n)).length := by + simp [poolWord, hw] + rw [and_iff_right hlen] + have hv (i : Fin r) : boolEquivF2 (AffineCode.rowValue (withSyndrome a.2 y) + (poolWord G (ScanRule.inputPrefix X n)) i.val) = + columnMap (columns a G.length r) (fun j => boolEquivF2 (X (G.get j))) i := by + change boolEquivF2 (parity (fun j => entry (rows a.2) i.val j && + (poolWord G (ScanRule.inputPrefix X n)).getD j false) (width a.2)) = _ + rw [hw, value_parity] + simp only [columnMap_apply, Finset.sum_apply, Pi.smul_apply, smul_eq_mul, columns] + apply Finset.sum_congr rfl + intro j _ + rw [value_and, getD_poolWord G _ j, + ScanRule.getD_inputPrefix X ((get_lt_bound G j).trans_le hn)] + exact mul_comm _ _ + change (∀ i < rank a.2, AffineCode.rowValue (withSyndrome a.2 y) + (poolWord G (ScanRule.inputPrefix X n)) i = y.getD i false) ↔ + (block G.get hG.injective_get a ha (wordVector r y)).matrix + (coordinateValues (fun i => i.val) X) = wordVector r y + rw [hr, block_matrix_coordinates G hG a ha] + constructor + · intro h + funext i + rw [← hv i, h i.val i.isLt] + rfl + · intro h i hi + apply boolEquivF2.injective + exact (hv ⟨i, hi⟩).trans (congrFun h ⟨i, hi⟩) + +/-- Actual reconstruction: compare finite truth tables and search for a +certified affine output code. -/ +def reconstruct (p : (List ℕ × Data) × List Bool) : Part Data := + StageCodeSearch.reconstruct (rank p.1.2) (bound p.1.1) (table p.1.1 p.1.2 p.2) + +theorem partrec_reconstruct : Partrec reconstruct := + StageCodeSearch.partrec_reconstruct + (computable_rank.comp (Computable.snd.comp Computable.fst)) + (computable_bound.comp (Computable.fst.comp Computable.fst)) computable_table.to₂ + +/-- Every checked candidate on a nodup actual pool is successfully recovered +with the same rank and exact event, for every supplied syndrome. -/ +theorem exists_reconstructed_code (G : List ℕ) (hG : G.Nodup) + {m r : ℕ} (a : Entry) (ha : GoodEntry G.length m r a) (y : List Bool) : + ∃ c ∈ reconstruct ((G, a.2), y), + valid c = true ∧ rank c = r ∧ + event c = (block G.get hG.injective_get a ha (wordVector r y)).event := by + have hbound : ∀ k ∈ (block G.get hG.injective_get a ha (wordVector r y)).support, + k < bound G := by + intro k hk + obtain ⟨j, _, rfl⟩ := Finset.mem_image.mp hk + exact get_lt_bound G j + have h := StageCodeSearch.exists_reconstructed_code + (block G.get hG.injective_get a ha (wordVector r y)) (bound G) hbound (table G a.2 y) + (table_inputPrefix G hG a ha y (bound G) le_rfl) + simpa only [reconstruct, ha.2.2.2.1, block_rank] using h + +end Klr.StageCandidateCode diff --git a/LeanPool/KLRandomness/StageChoice.lean b/LeanPool/KLRandomness/StageChoice.lean new file mode 100644 index 0000000000..0ca58877de --- /dev/null +++ b/LeanPool/KLRandomness/StageChoice.lean @@ -0,0 +1,299 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.StageWeights +public import LeanPool.KLRandomness.PrefixStage +public import LeanPool.KLRandomness.StageRankAverage +public import LeanPool.KLRandomness.PoolConstruction +import Mathlib.Tactic.NormNum +import Mathlib.Tactic.Positivity +import Mathlib.Tactic.Ring + +/-! +# Selecting one sparse candidate for both stage estimates + +The wager and rank-loss scores must be averaged over the same complete list. +Choosing an entry separately for the two scores would not prove the stage +construction. This file makes the joint finite averaging step explicit. +-/ + +@[expose] public section + +namespace Klr.StageChoice + +open MeasureTheory ProbabilityTheory +open scoped BigOperators ENNReal + +/-- One candidate simultaneously controls the sum of the two nonnegative +stage costs. Both average hypotheses refer to the same candidate family. -/ +theorem exists_combined_score_le {Q ι : Type*} [Fintype Q] [Nonempty Q] [Fintype ι] + (a b : Q → ι → ℝ) {d W R : ℝ} (hd : 0 ≤ d) + (ha : (∑ q, ∑ i, a q i) / Fintype.card Q ≤ W) + (hb : (∑ q, ∑ i, b q i) / Fintype.card Q ≤ R) : + ∃ q, (∑ i, (a q i + d * b q i)) ≤ W + d * R := by + classical + have hcard : (0 : ℝ) < Fintype.card Q := by exact_mod_cast Fintype.card_pos + have havg : (∑ q, ∑ i, (a q i + d * b q i)) / Fintype.card Q ≤ W + d * R := by + calc + _ = (∑ q, ∑ i, a q i) / Fintype.card Q + + d * ((∑ q, ∑ i, b q i) / Fintype.card Q) := by + simp_rw [Finset.sum_add_distrib, ← Finset.mul_sum] + ring + _ ≤ _ := add_le_add ha (mul_le_mul_of_nonneg_left hb hd) + have hs : (∑ q, ∑ i, (a q i + d * b q i)) ≤ ∑ _q : Q, (W + d * R) := by + simpa only [Finset.sum_const, Finset.card_univ, nsmul_eq_mul, mul_comm] using + (div_le_iff₀ hcard).mp havg + obtain ⟨q, _, hq⟩ := Finset.exists_le_of_sum_le Finset.univ_nonempty hs + exact ⟨q, hq⟩ + +/-- A small joint score controls the sum of all wager costs and each rank +cost, because every summand is nonnegative. -/ +theorem components_le_of_combined_score_le {ι : Type*} [Fintype ι] + (a b : ι → ℝ) {d C : ℝ} (ha : ∀ i, 0 ≤ a i) (hb : ∀ i, 0 ≤ b i) + (hd : 0 ≤ d) (h : (∑ i, (a i + d * b i)) ≤ C) : + (∑ i, a i) ≤ C ∧ ∀ i, d * b i ≤ C := by + classical + constructor + · apply le_trans _ h + exact Finset.sum_le_sum fun i _ => le_add_of_nonneg_right (mul_nonneg hd (hb i)) + · intro i + apply le_trans _ h + apply le_trans (le_add_of_nonneg_left (ha i)) + exact Finset.single_le_sum (fun j _ => add_nonneg (ha j) (mul_nonneg hd (hb j))) + (Finset.mem_univ i) + +/-- A fresh adaptive scan preserves fair coin on complete answer sequences. -/ +theorem fairCoin_map_observationMap (π : ScanRule) : + fairCoin.map π.observationMap = fairCoin := by + apply measure_eq_of_cylinders + intro v + rw [Measure.map_apply π.measurable_observationMap (measurableSet_cylinder v), + π.observationMap_preimage_cylinder] + exact (π.fairCoin_transcript v).trans (fairCoin_cylinder v).symm + +/-- Conditioning costs at most the reciprocal mass of the condition, also +for events specified in the complete adaptive answer sequence. -/ +theorem conditional_observationReal_le (A : Set Cantor) (hA : MeasurableSet A) + (π : ScanRule) (E : Set Cantor) (hE : MeasurableSet E) : + (cond fairCoin A).real (π.observationMap ⁻¹' E) ≤ + (fairCoin.real A)⁻¹ * fairCoin.real E := by + rw [measureReal_def, cond_apply hA, ENNReal.toReal_mul, ENNReal.toReal_inv] + change (fairCoin.real A)⁻¹ * fairCoin.real (A ∩ π.observationMap ⁻¹' E) ≤ _ + have hpre : fairCoin.real (π.observationMap ⁻¹' E) = fairCoin.real E := by + rw [← map_measureReal_apply π.measurable_observationMap hE, + fairCoin_map_observationMap] + rw [← hpre] + exact mul_le_mul_of_nonneg_left (measureReal_mono Set.inter_subset_right) + (inv_nonneg.mpr measureReal_nonneg) + +/-- The reciprocal mass of the previous equations is exactly two to their +total row rank. -/ +theorem prefixEvent_inverse_real (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) (n : ℕ) : + (fairCoin.real (PrefixStage.prefixEvent B n))⁻¹ = + (2 : ℝ) ^ (∑ k : Fin n, (B k).rank) := by + change (fairCoin (AffineBlock.familyEvent (PrefixStage.prefixFamily B n))).toReal⁻¹ = _ + rw [AffineBlock.fairCoin_familyEvent _ (PrefixStage.prefixFamily_pairwise B hdis n)] + simp only [ENNReal.toReal_prod, ENNReal.toReal_pow, ENNReal.toReal_div, + ENNReal.toReal_one, ENNReal.toReal_ofNat, PrefixStage.prefixFamily] + rw [Finset.prod_pow_eq_pow_sum, ← inv_pow] + norm_num + +/-- Every earlier finite-stage law obeys the same answer-event density +bound, with the total rank of the current prefix. -/ +theorem prefixLaw_observationReal_le (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) + (n a : ℕ) (ha : a ≤ n) (π : ScanRule) (E : Set Cantor) (hE : MeasurableSet E) : + (PrefixStage.law B a).real (π.observationMap ⁻¹' E) ≤ + (2 : ℝ) ^ (∑ k : Fin n, (B k).rank) * fairCoin.real E := by + have hmass : fairCoin.real (PrefixStage.prefixEvent B n) ≤ + fairCoin.real (PrefixStage.prefixEvent B a) := + measureReal_mono (PrefixStage.prefixEvent_antitone B ha) + have hpos : 0 < fairCoin.real (PrefixStage.prefixEvent B n) := + ENNReal.toReal_pos (PrefixStage.fairCoin_prefixEvent_ne_zero B hdis n) + (measure_ne_top _ _) + have hinv : (fairCoin.real (PrefixStage.prefixEvent B a))⁻¹ ≤ + (fairCoin.real (PrefixStage.prefixEvent B n))⁻¹ := by + simpa only [one_div] using one_div_le_one_div_of_le hpos hmass + calc + _ ≤ (fairCoin.real (PrefixStage.prefixEvent B a))⁻¹ * fairCoin.real E := + conditional_observationReal_le _ (PrefixStage.measurableSet_prefixEvent B a) π E hE + _ ≤ (fairCoin.real (PrefixStage.prefixEvent B n))⁻¹ * fairCoin.real E := + mul_le_mul_of_nonneg_right hinv measureReal_nonneg + _ = _ := by rw [prefixEvent_inverse_real B hdis n] + +/-- The pool positions in the original order returned by the pool program. -/ +def poolLabel (G : List ℕ) {M : ℕ} (hG : G.length = M) : Fin M → ℕ := + fun i => G.get (Fin.cast hG.symm i) + +theorem poolLabel_injective (G : List ℕ) {M : ℕ} (hG : G.length = M) (hn : G.Nodup) : + Function.Injective (poolLabel G hG) := by + intro i j hij + have h := hn.injective_get hij + exact Fin.ext (congrArg (fun k : Fin G.length => k.val) h) + +theorem poolLabel_image_univ (G : List ℕ) {M : ℕ} (hG : G.length = M) : + Finset.univ.image (poolLabel G hG) = G.toFinset := by + ext a + simp only [Finset.mem_image, Finset.mem_univ, true_and, List.mem_toFinset] + constructor + · rintro ⟨i, rfl⟩ + exact List.get_mem G _ + · intro ha + obtain ⟨i, hi⟩ := List.mem_iff_get.mp ha + exact ⟨Fin.cast hG i, by simpa [poolLabel] using hi⟩ + +/-- Expected total absolute normalized wager on a candidate's actual support. -/ +noncomputable def wagerCost (μ : Measure Cantor) (s : BettingStrategy) + (B : AffineBlock) : ℝ := + ∫ X, StageWeights.supportWager s.normalize.scan s.normalize.capital.wager B.support X ∂μ + +/-- Fair-coin probability of a rank drop on the low part of the answer space. -/ +noncomputable def lowDropCost (Low : Set Cantor) (s : BettingStrategy) + (B : AffineBlock) : ℝ := + fairCoin.real (Low ∩ (NoDrop.noDropTranscripts B s.normalize.scan)ᶜ) + +theorem wagerCost_nonneg (μ : Measure Cantor) (s : BettingStrategy) (B : AffineBlock) : + 0 ≤ wagerCost μ s B := + integral_nonneg fun X => StageWeights.supportWager_nonneg _ _ _ X + +theorem lowDropCost_nonneg (Low : Set Cantor) (s : BettingStrategy) (B : AffineBlock) : + 0 ≤ lowDropCost Low s B := measureReal_nonneg + +/-- The candidate-selection wager cost is independent of its syndrome. -/ +theorem wagerCost_listBlock_syndrome_irrel + {M m r J : ℕ} {τ θ : ℚ} {L : SparseListSearch.CodeList} + (hL : SparseListSearch.Good M m r J τ θ L) + (e : Fin M → ℕ) (he : Function.Injective e) + (y y' : Fin L.length → Fin r → ZMod 2) (j : Fin L.length) + (μ : Measure Cantor) (s : BettingStrategy) : + wagerCost μ s (StageRank.listBlock hL e he y j) = + wagerCost μ s (StageRank.listBlock hL e he y' j) := rfl + +/-- Full unread rank depends on the linear map, so the low-drop cost is +independent of the syndrome chosen later in the stage construction. -/ +theorem lowDropCost_listBlock_syndrome_irrel + {M m r J : ℕ} {τ θ : ℚ} {L : SparseListSearch.CodeList} + (hL : SparseListSearch.Good M m r J τ θ L) + (e : Fin M → ℕ) (he : Function.Injective e) + (y y' : Fin L.length → Fin r → ZMod 2) (j : Fin L.length) + (Low : Set Cantor) (s : BettingStrategy) : + lowDropCost Low s (StageRank.listBlock hL e he y j) = + lowDropCost Low s (StageRank.listBlock hL e he y' j) := rfl + +/-- The concrete sparse list contains one candidate controlling the wager +and low-part rank-drop costs for the entire protected family at once. -/ +theorem exists_candidate_joint_bound {ι : Type*} [Fintype ι] + (μ : Measure Cantor) [IsProbabilityMeasure μ] + {M m r J : ℕ} {τ θ : ℚ} {L : SparseListSearch.CodeList} + (hL : SparseListSearch.Good M m r J τ θ L) (hJ : 0 < J) (hθ : 0 ≤ θ) + (e : Fin M → ℕ) (he : Function.Injective e) + (y : Fin L.length → Fin r → ZMod 2) + (s : ι → BettingStrategy) (Low : ι → Set Cantor) + (hLow : ∀ i, MeasurableSet (Low i)) (η : ℝ) + (hpool : ∀ i, fairCoin.real {Z | Z ∈ Low i ∧ + (PoolQuery.missedCount (s i).normalize.scan (Finset.univ.image e) Z : ℝ) < + (τ : ℝ) * M} ≤ η) {d : ℝ} (hd : 0 ≤ d) : + ∃ j : Fin L.length, + (∑ i, (wagerCost μ (s i) (StageRank.listBlock hL e he y j) + + d * lowDropCost (Low i) (s i) (StageRank.listBlock hL e he y j))) ≤ + (Fintype.card ι : ℝ) * + ((2 * ((m : ℝ) / M)) * Real.sqrt ((M : ℝ) / 2) + d * (η + (θ : ℝ))) := by + classical + let a (j : Fin L.length) (i : ι) := wagerCost μ (s i) (StageRank.listBlock hL e he y j) + let b (j : Fin L.length) (i : ι) := lowDropCost (Low i) (s i) (StageRank.listBlock hL e he y j) + have hlen : 0 < L.length := by simpa only [hL.1] using hJ + let : Nonempty (Fin L.length) := ⟨⟨0, hlen⟩⟩ + have ha : (∑ j, ∑ i, a j i) / Fintype.card (Fin L.length) ≤ + (Fintype.card ι : ℝ) * ((2 * ((m : ℝ) / M)) * Real.sqrt ((M : ℝ) / 2)) := by + simpa only [a, wagerCost, StageRank.listBlock, StageCandidate.block_support, + Fintype.card_fin, hL.1] using + StageWeights.average_integral_normalized_supportWager_le μ hL hJ s e he + have hb : (∑ j, ∑ i, b j i) / Fintype.card (Fin L.length) ≤ + (Fintype.card ι : ℝ) * (η + (θ : ℝ)) := by + have hcard : Fintype.card (Fin L.length) = J := by simpa only [Fintype.card_fin] using hL.1 + rw [hcard, Finset.sum_comm, Finset.sum_div] + calc + _ ≤ ∑ _i : ι, (η + (θ : ℝ)) := Finset.sum_le_sum fun i _ => + StageRank.average_measureReal_low_hasDrop_le hL hJ hθ e he y + (s i).normalize.scan (Low i) (hLow i) η (hpool i) + _ = _ := by simp only [Finset.sum_const, Finset.card_univ, nsmul_eq_mul] + obtain ⟨j, hj⟩ := exists_combined_score_le a b hd ha hb + refine ⟨j, hj.trans_eq ?_⟩ + ring + +/-- Actual accepted pool data discharge the low-part hypothesis of the +joint candidate choice. The list order supplies the injective pool labels. -/ +theorem exists_candidate_joint_bound_of_goodPool + (μ : Measure Cantor) [IsProbabilityMeasure μ] + {M m r J ℓ z : ℕ} {τ θ : ℚ} {L : SparseListSearch.CodeList} {G : List ℕ} + (hL : SparseListSearch.Good M m r J τ θ L) (hJ : 0 < J) (hθ : 0 ≤ θ) + (s : ℕ → BettingStrategy) (H : ℕ → Set Cantor) + (hH : ∀ i < ℓ, MeasurableSet (H i)) (η : ℝ) + (hG : PoolConstruction.GoodPool (fun i => (s i).normalize.scan) H ℓ η z τ M G) + (y : Fin L.length → Fin r → ZMod 2) {d : ℝ} (hd : 0 ≤ d) : + ∃ j : Fin L.length, + (∑ i : Fin ℓ, + (wagerCost μ (s i) (StageRank.listBlock hL (poolLabel G hG.1) + (poolLabel_injective G hG.1 hG.2.1) y j) + + d * lowDropCost (H i)ᶜ (s i) (StageRank.listBlock hL (poolLabel G hG.1) + (poolLabel_injective G hG.1 hG.2.1) y j))) ≤ + (ℓ : ℝ) * + ((2 * ((m : ℝ) / M)) * Real.sqrt ((M : ℝ) / 2) + d * (η + (θ : ℝ))) := by + have hpool (i : Fin ℓ) : fairCoin.real {Z | Z ∈ (H i)ᶜ ∧ + (PoolQuery.missedCount (s i).normalize.scan (Finset.univ.image (poolLabel G hG.1)) Z : ℝ) < + (τ : ℝ) * M} ≤ η := by + rw [poolLabel_image_univ] + exact (hG.2.2.2 i i.isLt).2.le + simpa only [Fintype.card_fin] using exists_candidate_joint_bound μ hL hJ hθ + (poolLabel G hG.1) (poolLabel_injective G hG.1 hG.2.1) y + (fun i : Fin ℓ => s i) (fun i : Fin ℓ => (H i)ᶜ) + (fun i => (hH i i.isLt).compl) η hpool hd + +/-- The selected joint score bounds all the low-drop probabilities under +every earlier stage law, as well as the total expected wager cost. -/ +theorem prior_stage_costs_le_of_joint_bound {ι : Type*} [Fintype ι] + (μ : Measure Cantor) (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) + (n : ℕ) (s : ι → BettingStrategy) (Low : ι → Set Cantor) + (hLow : ∀ i, MeasurableSet (Low i)) (C : AffineBlock) {ε : ℝ} + (hscore : (∑ i, (wagerCost μ (s i) C + + (2 : ℝ) ^ (∑ k : Fin n, (B k).rank) * lowDropCost (Low i) (s i) C)) ≤ ε) : + (∑ i, wagerCost μ (s i) C) ≤ ε ∧ + ∀ i a, a ≤ n → (PrefixStage.law B a).real + ((s i).normalize.scan.observationMap ⁻¹' + (Low i ∩ (NoDrop.noDropTranscripts C (s i).normalize.scan)ᶜ)) ≤ ε := by + have hcomp := components_le_of_combined_score_le + (fun i => wagerCost μ (s i) C) (fun i => lowDropCost (Low i) (s i) C) + (fun i => wagerCost_nonneg μ (s i) C) (fun i => lowDropCost_nonneg (Low i) (s i) C) + (by positivity) hscore + refine ⟨hcomp.1, ?_⟩ + intro i a ha + exact (prefixLaw_observationReal_le B hdis n a ha (s i).normalize.scan _ + ((hLow i).inter (NoDrop.measurableSet_noDropTranscripts _ _).compl)).trans (hcomp.2 i) + +/-- Every positive-rank candidate inside a good pool has small high-part +no-drop mass; this estimate requires no further candidate selection. -/ +theorem high_noDrop_measureReal_lt_of_goodPool + {M ℓ z : ℕ} {τ : ℚ} {G : List ℕ} {η : ℝ} + {π : ℕ → ScanRule} {H : ℕ → Set Cantor} + (hG : PoolConstruction.GoodPool π H ℓ η z τ M G) + (C : AffineBlock) (hCG : C.support ⊆ G.toFinset) (hr : 0 < C.rank) + (i : ℕ) (hi : i < ℓ) : + fairCoin.real (H i ∩ NoDrop.noDropTranscripts C (π i)) < η := by + have hsub : H i ∩ NoDrop.noDropTranscripts C (π i) ⊆ + {Z | Z ∈ H i ∧ ∃ b ∈ G, ¬ PoolQuery.Reads (π i) b Z} := by + intro Z hZ + have hmiss := StageRank.noDropTranscripts_subset_missed C (π i) G.toFinset hCG hr hZ.2 + obtain ⟨b, hb, hnb⟩ := (PoolQuery.missedCount_pos_iff (π i) G.toFinset Z).mp hmiss + exact ⟨hZ.1, b, List.mem_toFinset.mp hb, hnb⟩ + exact (measureReal_mono hsub).trans_lt (hG.2.2.2 i hi).1 + +end Klr.StageChoice diff --git a/LeanPool/KLRandomness/StageCodeSearch.lean b/LeanPool/KLRandomness/StageCodeSearch.lean new file mode 100644 index 0000000000..0709d20930 --- /dev/null +++ b/LeanPool/KLRandomness/StageCodeSearch.lean @@ -0,0 +1,171 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.StageFiniteProbability +public import LeanPool.KLRandomness.AffineCodeCoverage + +/-! +# Effective reconstruction of a bounded affine event + +An affine block with bounded support can be output as a certified ordinary +code by exhaustive finite truth-table comparison. This avoids treating a +noncomputably chosen matrix representation as part of the reconstruction +program. The input to the program is only the rank, a coordinate bound, and +the parameters of a computable Boolean predicate on prefixes. +-/ + +@[expose] public section + +namespace Klr.StageCodeSearch + +open AffineCode FiniteMeasure SparseSearch + +/-- Every affine block whose support lies below `n` has a certified code of +exactly that width. The witness is used to prove search termination. -/ +theorem exists_valid_code_bounded (B : AffineBlock) (n : ℕ) + (hn : ∀ k ∈ B.support, k < n) : + ∃ c : Data, width c = n ∧ rank c = B.rank ∧ valid c = true ∧ event c = B.event := by + classical + let restrict : (Fin n → ZMod 2) →ₗ[ZMod 2] (B.support → ZMod 2) := + { toFun := fun x i => x ⟨i.val, hn i.val i.property⟩ + map_add' := fun _ _ => rfl + map_smul' := fun _ _ => rfl } + have hrestrict : Function.Surjective restrict := by + intro x + refine ⟨fun j => if hj : j.val ∈ B.support then x ⟨j.val, hj⟩ else 0, ?_⟩ + funext i + change (if hi : i.val ∈ B.support then x ⟨i.val, hi⟩ else 0) = x i + simp [i.property] + let D := B.matrix.comp restrict + let A := LinearMap.toMatrix' D + have hA : Function.Surjective A.mulVecLin := by + intro y + obtain ⟨x, hx⟩ := B.fullRank y + obtain ⟨v, hv⟩ := hrestrict x + refine ⟨v, ?_⟩ + change Matrix.mulVec (LinearMap.toMatrix' D) v = y + rw [LinearMap.toMatrix'_mulVec] + change B.matrix (restrict v) = y + rw [hv, hx] + obtain ⟨c, hw, hr, hv, he⟩ := exists_valid_code A hA B.syndrome + refine ⟨c, hw, hr, hv, he.trans ?_⟩ + ext X + change Matrix.mulVec (LinearMap.toMatrix' D) + (coordinateValues (fun i : Fin n => i.val) X) = B.syndrome ↔ _ + rw [LinearMap.toMatrix'_mulVec] + rfl + +/-- The finite verifier requires both a right-inverse certificate and exact +agreement with the target truth table. -/ +def check (r n : ℕ) (p : List Bool → Bool) (c : Data) : Bool := + valid c && (decide (rank c = r) && (decide (width c ≤ n) && + (words n).all (fun s => decide (accepts c s = p s)))) + +theorem check_eq_true (r n : ℕ) (p : List Bool → Bool) (c : Data) : + check r n p c = true ↔ valid c = true ∧ rank c = r ∧ width c ≤ n ∧ + ∀ s, s.length = n → accepts c s = p s := by + simp only [check, Bool.and_eq_true, decide_eq_true_eq, List.all_eq_true, mem_words_iff] + +theorem computable_check {α : Type*} [Primcodable α] + {r n : α → ℕ} {p : α → List Bool → Bool} + (hr : Computable r) (hn : Computable n) (hp : Computable₂ p) : + Computable₂ (fun a c => check (r a) (n a) (p a) c) := by + have hc : Computable (fun z : (α × Data) × List Bool => z.1.2) := + Computable.snd.comp Computable.fst + have ht := Primrec.eq.decide.to_comp.comp + (computable_accepts.comp hc Computable.snd) + (hp.comp (Computable.fst.comp Computable.fst) Computable.snd) + have hall := computable_list_all + (p := fun z : α × Data => fun s => decide (accepts z.2 s = p z.1 s)) + (computable_words.comp (hn.comp Computable.fst)) ht.to₂ + have hwidth := Primrec.nat_le.decide.to_comp.comp + (computable_width.comp Computable.snd) (hn.comp Computable.fst) + have hrank := Primrec.eq.decide.to_comp.comp + (computable_rank.comp Computable.snd) (hr.comp Computable.fst) + exact Primrec.and.to_comp.comp (computable_valid.comp Computable.snd) + (Primrec.and.to_comp.comp hrank (Primrec.and.to_comp.comp hwidth hall)) + +/-- Decode a candidate number and return its affine code if it passes the checks. -/ +def trial (r n : ℕ) (p : List Bool → Bool) (k : ℕ) : Option Data := + (Encodable.decode k).bind (fun c => if check r n p c then some c else none) + +/-- Search for the first coded affine system that satisfies the target finite test. -/ +def reconstruct (r n : ℕ) (p : List Bool → Bool) : Part Data := + Nat.rfindOpt (trial r n p) + +theorem computable_trial {α : Type*} [Primcodable α] + {r n : α → ℕ} {p : α → List Bool → Bool} + (hr : Computable r) (hn : Computable n) (hp : Computable₂ p) : + Computable₂ (fun a k => trial (r a) (n a) (p a) k) := by + have hc := computable_check hr hn hp + have hf : Computable₂ (fun a c => if check (r a) (n a) (p a) c then some c else none) := by + exact (Computable.cond hc (Computable.option_some.comp Computable.snd) + (Computable.const none)).of_eq fun _ => by simp only [Bool.cond_eq_ite] + exact Computable.bind_decode_iff.mpr hf + +/-- A single partial recursive reconstruction algorithm works for every +computable family of target finite truth tables. -/ +theorem partrec_reconstruct {α : Type*} [Primcodable α] + {r n : α → ℕ} {p : α → List Bool → Bool} + (hr : Computable r) (hn : Computable n) (hp : Computable₂ p) : + Partrec (fun a => reconstruct (r a) (n a) (p a)) := + Partrec.rfindOpt (computable_trial hr hn hp) + +theorem reconstruct_spec {r n : ℕ} {p : List Bool → Bool} {c : Data} + (hc : c ∈ reconstruct r n p) : + valid c = true ∧ rank c = r ∧ width c ≤ n ∧ + ∀ s, s.length = n → accepts c s = p s := by + obtain ⟨k, hk⟩ := Nat.rfindOpt_spec hc + simp only [trial, Option.mem_bind_iff] at hk + obtain ⟨d, _, hd⟩ := hk + split_ifs at hd with hv + · have he : d = c := Option.mem_some_iff.mp hd + subst d + exact (check_eq_true r n p c).mp hv + · simp at hd + +theorem inputPrefix_getD (s : List Bool) : + ScanRule.inputPrefix (fun k => s.getD k false) s.length = s := by + apply List.ext_getElem (by simp) + intro i hi hj + rw [← List.getD_eq_getElem _ false hi, ← List.getD_eq_getElem _ false hj, + ScanRule.getD_inputPrefix _ (by simpa using hi)] + +/-- The algorithm halts for an actual bounded affine block and returns exactly +its event, at exactly its rank, with a checked right-inverse certificate. -/ +theorem exists_reconstructed_code (B : AffineBlock) (n : ℕ) + (hn : ∀ k ∈ B.support, k < n) (p : List Bool → Bool) + (hp : ∀ X, p (ScanRule.inputPrefix X n) = true ↔ X ∈ B.event) : + ∃ c ∈ reconstruct B.rank n p, + valid c = true ∧ rank c = B.rank ∧ event c = B.event := by + obtain ⟨d, hdw, hdr, hdv, hde⟩ := exists_valid_code_bounded B n hn + have hcheck : check B.rank n p d = true := by + apply (check_eq_true _ _ _ _).mpr + refine ⟨hdv, hdr, hdw.le, ?_⟩ + intro s hs + rw [Bool.eq_iff_iff] + have hx := StageFiniteProbability.accepts_code_inputPrefix d n hdw.le + (fun k => s.getD k false) + have hxp := hp (fun k => s.getD k false) + rw [← hs, inputPrefix_getD] at hx hxp + exact hx.trans (hde ▸ hxp.symm) + have hdom : (reconstruct B.rank n p).Dom := by + apply Nat.rfindOpt_dom.mpr + refine ⟨Encodable.encode d, d, ?_⟩ + simp [trial, hcheck] + obtain ⟨c, hc⟩ := Part.dom_iff_mem.mp hdom + obtain ⟨hcv, hcr, hcw, hcp⟩ := reconstruct_spec hc + refine ⟨c, hc, hcv, hcr, ?_⟩ + ext X + rw [← StageFiniteProbability.accepts_code_inputPrefix c n hcw X, + hcp _ (ScanRule.length_inputPrefix X n)] + exact hp X + +end Klr.StageCodeSearch diff --git a/LeanPool/KLRandomness/StageConditionalScan.lean b/LeanPool/KLRandomness/StageConditionalScan.lean new file mode 100644 index 0000000000..9107ebc25c --- /dev/null +++ b/LeanPool/KLRandomness/StageConditionalScan.lean @@ -0,0 +1,98 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.StageCandidateCode +public import LeanPool.KLRandomness.StageFiniteCondition +public import LeanPool.KLRandomness.StageFiniteScan + +/-! +# Computable expectations after adding a candidate syndrome + +The conditioning predicate is evaluated directly on the old affine codes +and the candidate matrix on its concrete pool. Every possible syndrome can +therefore be compared before a certified output code has been reconstructed. +-/ + +@[expose] public section + +namespace Klr.StageConditionalScan + +open MeasureTheory ProbabilityTheory SparseSearch SparseListSearch StageCandidate + +/-- A prefix length determining the scan and the affine conditions. -/ +def depth (cs : List AffineCode.Data) (G : List ℕ) (π : ScanRule) (V : ℕ) : ℕ := + StageFiniteScan.depth cs π V + StageCandidateCode.bound G + +/-- The finite test for simultaneous satisfaction of old and new affine conditions. -/ +def accepts (cs : List AffineCode.Data) (G : List ℕ) (c : AffineCode.Data) + (y s : List Bool) : Bool := + StageFiniteProbability.accepts cs s && StageCandidateCode.table G c y s + +/-- The exact rational conditional average of a prefix function. -/ +def expectation (cs : List AffineCode.Data) (G : List ℕ) (c : AffineCode.Data) + (y : List Bool) (π : ScanRule) (V : ℕ) (f : List Bool → ℚ) : ℚ := + StageFiniteCondition.expectation (depth cs G π V) (accepts cs G c y) + (fun s => f (StageFiniteScan.run π s V)) + +theorem computable_expectation (π : ScanRule) {α : Type*} [Primcodable α] + {cs : α → List AffineCode.Data} {G : α → List ℕ} {c : α → AffineCode.Data} + {y : α → List Bool} {V : α → ℕ} {f : α → List Bool → ℚ} + (hcs : Computable cs) (hG : Computable G) (hc : Computable c) + (hy : Computable y) (hV : Computable V) (hf : Computable₂ f) : + Computable (fun a => expectation (cs a) (G a) (c a) (y a) π (V a) (f a)) := by + have hn := Primrec.nat_add.to_comp.comp + ((StageFiniteScan.computable_depth π).comp (hcs.pair hV)) + (StageCandidateCode.computable_bound.comp hG) + have hold := StageFiniteProbability.computable_accepts.comp + (hcs.comp Computable.fst) Computable.snd + have hnew := StageCandidateCode.computable_table.comp + ((((hG.comp Computable.fst).pair (hc.comp Computable.fst)).pair + (hy.comp Computable.fst)).pair Computable.snd) + have hp := Primrec.and.to_comp.comp hold hnew + have hr := (StageFiniteScan.computable_run π).comp Computable.snd (hV.comp Computable.fst) + exact StageFiniteCondition.computable_expectation hn hp (hf.comp Computable.fst hr) + +/-- The finite Boolean condition is exactly old constraints intersected with +the selected affine event. -/ +theorem event_eq (cs : List AffineCode.Data) (G : List ℕ) (hG : G.Nodup) + {m r : ℕ} (a : Entry) (ha : GoodEntry G.length m r a) + (y : List Bool) (π : ScanRule) (V : ℕ) : + StageFiniteCondition.event (depth cs G π V) (accepts cs G a.2 y) = + StageFiniteProbability.event cs ∩ + (block G.get hG.injective_get a ha (wordVector r y)).event := by + ext X + change (StageFiniteProbability.accepts cs (ScanRule.inputPrefix X (depth cs G π V)) && + StageCandidateCode.table G a.2 y (ScanRule.inputPrefix X (depth cs G π V))) = true ↔ _ + unfold depth + rw [Bool.and_eq_true, + StageFiniteProbability.accepts_inputPrefix cs _ (fun c hc => + (StageFiniteScan.width_le_depth π V hc).trans (Nat.le_add_right _ _)), + StageCandidateCode.table_inputPrefix G hG a ha y _ (Nat.le_add_left _ _) X] + rfl + +/-- Exact rational evaluation under the actual old law conditioned on the +new candidate syndrome. No affine output code is assumed in this identity. -/ +theorem expectation_eq_integral (cs : List AffineCode.Data) (G : List ℕ) (hG : G.Nodup) + {m r : ℕ} (a : Entry) (ha : GoodEntry G.length m r a) + (y : List Bool) (π : ScanRule) (V : ℕ) (f : List Bool → ℚ) : + (expectation cs G a.2 y π V f : ℝ) = + ∫ X, (f (π.transcript X V) : ℝ) ∂cond (StageFiniteProbability.law cs) + (block G.get hG.injective_get a ha (wordVector r y)).event := by + rw [expectation, StageFiniteCondition.expectation_eq_integral, event_eq cs G hG a ha] + rw [StageFiniteProbability.law, cond_cond_eq_cond_inter + (StageFiniteProbability.measurableSet_event cs) + (block G.get hG.injective_get a ha (wordVector r y)).measurableSet_event fairCoin] + apply integral_congr_ae + filter_upwards [] with X + unfold depth + rw [StageFiniteScan.run_inputPrefix_of_bound π V _ (fun v hv => + (StageFiniteScan.query_lt_depth cs π V v hv).trans_le (Nat.le_add_right _ _)) X le_rfl] + +end Klr.StageConditionalScan diff --git a/LeanPool/KLRandomness/StageConstruction.lean b/LeanPool/KLRandomness/StageConstruction.lean new file mode 100644 index 0000000000..c694fef708 --- /dev/null +++ b/LeanPool/KLRandomness/StageConstruction.lean @@ -0,0 +1,73 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.StageOneStep +public import LeanPool.KLRandomness.StageRecursion + +/-! +# The completed stage construction + +The Borel partitions are fixed before any stage is chosen. For every finite +history, preparation supplies a candidate and a fixed reconstruction program; +the one-step theorem supplies its actual horizon, syndrome and short output. +Enlarging the requested cutoff separates the new block from every old support. +This discharges the extension premise of the global recursion. +-/ + +@[expose] public section + +noncomputable section + +namespace Klr.StageConstruction + +open MeasureTheory + +/-- One fixed family of Borel partitions admits an actual, fully represented +extension after every disjoint finite history and beyond every requested cutoff. -/ +theorem exists_fixed_partitions_steps (s : ℕ → BettingStrategy) : + ∃ H : ℕ → Set Cantor, (∀ i, MeasurableSet (H i)) ∧ + ∀ old : ℕ → AffineBlock, + Pairwise (fun i j => Disjoint (old i).support (old j).support) → + ∀ n z : ℕ, ∃ C V, + StageRecursion.Step s H old n z (StageErrorBudget.rational n) C V := by + obtain ⟨H, hH, hprepared⟩ := StagePrepared.exists_fixed_partitions_prepared s + refine ⟨H, hH, ?_⟩ + intro old hold n z + let z' := max z ((PrefixStage.prefixSupport old n).sup id + 1) + have hz : ∀ k < n, ∀ p ∈ (old k).support, p < z' := by + intro k hk p hp + have hmem : p ∈ PrefixStage.prefixSupport old n := + (PrefixStage.mem_prefixSupport old n p).mpr ⟨k, hk, hp⟩ + have hle : p ≤ (PrefixStage.prefixSupport old n).sup id := + Finset.le_sup (f := id) hmem + exact lt_of_lt_of_le (Nat.lt_succ_of_le hle) (le_max_right _ _) + obtain ⟨P⟩ := hprepared old hold n z' (StageErrorBudget.rational n) + (StageErrorBudget.rational_pos n) + obtain ⟨C, V, hstep⟩ := P.to_step hold (StageErrorBudget.rational_pos n) hz + refine ⟨C, V, { hstep with above := ?_ }⟩ + intro p hp + exact (le_max_left z _).trans (hstep.above p hp) + +/-- The actual infinite block sequence has every required estimate and one +short exact affine description at each Martin-Löf test level. -/ +theorem exists_sequence (s : ℕ → BettingStrategy) : + ∃ (H : ℕ → Set Cantor) (B : ℕ → AffineBlock) (V : ℕ → ℕ), + (∀ i, MeasurableSet (H i)) ∧ + Pairwise (fun i j => Disjoint (B i).support (B j).support) ∧ + (∀ i, StageEstimates B (s i).normalize.scan + (s i).normalize.capital.wager V (H i) i) ∧ + ∀ n : ℕ, ∃ (p : List Bool) (c : AffineCode.Data), + c ∈ AffineDescription.run p ∧ AffineCode.valid c = true ∧ + 2 * p.length + n + 1 ≤ AffineCode.rank c ∧ AffineCode.event c = (B n).event := by + obtain ⟨H, hH, hstep⟩ := exists_fixed_partitions_steps s + obtain ⟨B, V, hdis, hest, hprogram⟩ := StageRecursion.exists_sequence s H hstep hH + exact ⟨H, B, V, hH, hdis, hest, hprogram⟩ + +end Klr.StageConstruction diff --git a/LeanPool/KLRandomness/StageEnumeration.lean b/LeanPool/KLRandomness/StageEnumeration.lean new file mode 100644 index 0000000000..858141f3b3 --- /dev/null +++ b/LeanPool/KLRandomness/StageEnumeration.lean @@ -0,0 +1,48 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.StrategyCountability +import Mathlib.Tactic.NormNum + +/-! +# A classical enumeration of every total betting strategy + +Only a countable covering enumeration is needed by the stage construction. +Each finite protected list contains individually computable strategies; no +effective enumeration of all total programs is claimed or used. +-/ + +@[expose] public section + +namespace Klr.StageEnumeration + +/-- A strategy which scans in order and never changes its unit capital. -/ +def idle : BettingStrategy where + scan := ScanRule.monotone + capital := { + value := fun _ => 1 + initial := rfl + nonneg := fun _ => by norm_num + fair := fun _ => by norm_num } + computable_capital := by + refine ⟨fun _ _ => 1, Computable.const ((1 : ℚ).num, (1 : ℚ).den), ?_⟩ + intro v n + simp + +/-- The genuinely countable total-strategy type has a surjective natural +enumeration, chosen classically. This is not an effective program listing. -/ +theorem exists_surjective : ∃ s : ℕ → BettingStrategy, Function.Surjective s := by + classical + let : Encodable BettingStrategy := Encodable.ofCountable BettingStrategy + let s (n : ℕ) : BettingStrategy := (Encodable.decode n).getD idle + refine ⟨s, fun t => ⟨Encodable.encode t, ?_⟩⟩ + simp [s] + +end Klr.StageEnumeration diff --git a/LeanPool/KLRandomness/StageErrorBudget.lean b/LeanPool/KLRandomness/StageErrorBudget.lean new file mode 100644 index 0000000000..76020b5988 --- /dev/null +++ b/LeanPool/KLRandomness/StageErrorBudget.lean @@ -0,0 +1,135 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.LateDropBound +public import Mathlib.Analysis.SpecificLimits.Basic +import Mathlib.Tactic.NormNum +import Mathlib.Tactic.Ring + +/-! +# The dyadic stage error budget + +The paper's errors are `e_j = 2^(-j) / 100`. Their strict tail equals the +current error. The four contributions to the Section 6 late-drop estimate +therefore total `8e_j`, while the early-wager estimate uses `4e_j`. Both +series have finite sums, including after any finite set of initial stages. + +The final theorem specializes the actual finite-stage estimate in +`LateDropBound`; it does not assert that suitable stages have been chosen. +-/ + +@[expose] public section + +namespace Klr.StageErrorBudget + +open MeasureTheory +open scoped ENNReal NNReal + +/-- The error assigned to stage `j`. -/ +noncomputable def error (j : ℕ) : ℝ≥0∞ := (1 / 2 : ℝ≥0∞) ^ j / 100 + +theorem error_pos (j : ℕ) : 0 < error j := by + unfold error + exact ENNReal.div_pos (pow_ne_zero _ (by norm_num)) (by norm_num) + +theorem error_lt_top (j : ℕ) : error j < ∞ := by + unfold error + finiteness + +/-- The total error budget, with stages indexed starting at zero. -/ +theorem tsum_error : (∑' j : ℕ, error j) = (1 / 50 : ℝ≥0∞) := by + simp_rw [error, div_eq_mul_inv] + rw [ENNReal.tsum_mul_right, ENNReal.tsum_geometric] + norm_num + simpa [ENNReal.coe_inv] using congrArg (fun x : ℝ≥0 => (x : ℝ≥0∞)) + (by norm_num : (2 : ℝ≥0) * 100⁻¹ = 50⁻¹) + +theorem tsum_error_lt_top : (∑' j : ℕ, error j) < ∞ := by + rw [tsum_error] + norm_num + +/-- Any finite multiple of the stage-error series has finite sum. -/ +theorem tsum_mul_error_lt_top (c : ℝ≥0∞) (hc : c < ∞) : + (∑' j : ℕ, c * error j) < ∞ := by + rw [ENNReal.tsum_mul_left] + exact ENNReal.mul_lt_top hc tsum_error_lt_top + +/-- Exact shifted sum; finite exceptional stages can be discarded freely. -/ +theorem tsum_error_shift (J : ℕ) : + (∑' j : ℕ, error (j + J)) = 2 * error J := by + simp_rw [error, pow_add, div_eq_mul_inv] + rw [ENNReal.tsum_mul_right, ENNReal.tsum_mul_right, ENNReal.tsum_geometric] + norm_num + ac_rfl + +theorem tsum_mul_error_shift_lt_top (c : ℝ≥0∞) (hc : c < ∞) (J : ℕ) : + (∑' j : ℕ, c * error (j + J)) < ∞ := by + rw [ENNReal.tsum_mul_left, tsum_error_shift] + exact ENNReal.mul_lt_top hc (ENNReal.mul_lt_top (by norm_num) (error_lt_top J)) + +/-- The natural-number enumeration of the stages strictly after `j`. -/ +def laterEquiv (j : ℕ) : ℕ ≃ {k : ℕ // j < k} where + toFun n := ⟨n + (j + 1), by omega⟩ + invFun k := k.val - (j + 1) + left_inv n := by dsimp; omega + right_inv k := by apply Subtype.ext; dsimp; omega + +/-- For this dyadic budget, the strict tail equals the current term. -/ +theorem tail_error (j : ℕ) : + (∑' k : {k : ℕ // j < k}, error k.val) = error j := by + rw [← (laterEquiv j).tsum_eq (fun k => error k.val)] + change (∑' n : ℕ, error (n + (j + 1))) = error j + rw [tsum_error_shift] + unfold error + simp only [pow_succ, div_eq_mul_inv, one_mul] + calc + _ = ((2 : ℝ≥0∞) * 2⁻¹) * (2⁻¹ ^ j * 100⁻¹) := by ac_rfl + _ = _ := by rw [ENNReal.mul_inv_cancel (by norm_num) (by norm_num), one_mul] + +/-- The four terms in the late-drop bound collapse to `8e_j`. -/ +theorem late_budget (j : ℕ) : + 4 * error j + 2 * error j + error j + + (∑' k : {k : ℕ // j < k}, error k.val) = 8 * error j := by + rw [tail_error] + ring + +theorem tsum_four_error : (∑' j : ℕ, 4 * error j) = (2 / 25 : ℝ≥0∞) := by + rw [ENNReal.tsum_mul_left, tsum_error] + norm_num + simpa [ENNReal.coe_inv, ENNReal.coe_div] using + congrArg (fun x : ℝ≥0 => (x : ℝ≥0∞)) + (by norm_num : (4 : ℝ≥0) * 50⁻¹ = 2 / 25) + +theorem tsum_eight_error : (∑' j : ℕ, 8 * error j) = (4 / 25 : ℝ≥0∞) := by + rw [ENNReal.tsum_mul_left, tsum_error] + norm_num + simpa [ENNReal.coe_inv, ENNReal.coe_div] using + congrArg (fun x : ℝ≥0 => (x : ℝ≥0∞)) + (by norm_num : (8 : ℝ≥0) * 50⁻¹ = 4 / 25) + +/-- The paper's numerical late-drop estimate under its actual stage hypotheses. -/ +theorem law_lateEvent_le_dyadic (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) + (π : ScanRule) (V : ℕ → ℕ) (j : ℕ) (H : Set Cantor) (hH : MeasurableSet H) + (havoid : ∀ v, v.length = V j → ∀ k, j < k → (B k).UnreadFullRank π v) + (hpartial : PrefixStage.law B (j + 1) + (LateDropBound.partialEvent (B j) π (V j)) ≤ 4 * error j) + (htail : PrefixStage.law B (j + 1) + (StoppingTranscript.rankDropTailEvent (B j) π (V j)) ≤ 2 * error j) + (hhigh : PrefixStage.law B j + (π.observationMap ⁻¹' H ∩ NoDrop.noDropEvent (B j) π) ≤ error j) + (hlater : ∀ k, j < k → PrefixStage.law B (j + 1) + (π.observationMap ⁻¹' Hᶜ ∩ LateDropBound.hasDrop (B k) π) ≤ error k) : + BlockProduct.law B hdis (DropEvents.lateEvent B π V j) ≤ 8 * error j := by + simpa only [late_budget] using + LateDropBound.law_lateEvent_le B hdis π V j H hH + (4 * error j) (2 * error j) (error j) error havoid hpartial htail hhigh hlater + +end Klr.StageErrorBudget diff --git a/LeanPool/KLRandomness/StageEstimates.lean b/LeanPool/KLRandomness/StageEstimates.lean new file mode 100644 index 0000000000..53eccdc426 --- /dev/null +++ b/LeanPool/KLRandomness/StageEstimates.lean @@ -0,0 +1,136 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.BlockRandomness +public import LeanPool.KLRandomness.HorizonLaw +public import LeanPool.KLRandomness.StageErrorBudget +import Mathlib.Tactic.NormNum +import Mathlib.Tactic.Ring + +/-! +# The stage-construction contract and the separation reduction + +`StageEstimates` records the actual finite-stage estimates (6)--(9), together +with horizon avoidance, for one scan and wager function beyond an arbitrary +finite block index. It is a proposition about supplied blocks, not an assertion +that blocks with these properties exist. + +These estimates imply the actual infinite-law early and late bounds, then +almost-sure summability of all forced wagers. If they hold for every normalized +strategy and the block solutions have the stated effective description cover, +the final separating-sequence conclusion follows. `StageConstruction` now +supplies this contract using actual pools, candidates and short descriptions. +-/ + +@[expose] public section + +namespace Klr + +open MeasureTheory +open scoped ENNReal + +/-- The Section 5 output needed for one strategy. Stage `j + 1` includes block `j`; +the finite exceptional prefix before `J` needs no estimates. -/ +structure StageEstimates (B : ℕ → AffineBlock) (π : ScanRule) (w : List Bool → ℝ) + (V : ℕ → ℕ) (H : Set Cantor) (J : ℕ) : Prop where + measurableH : MeasurableSet H + horizon_avoidance : ∀ j, J ≤ j → ∀ v, v.length = V j → + ∀ k, j < k → (B k).UnreadFullRank π v + early_and_partial : ∀ j, J ≤ j → + (∫⁻ X, ENNReal.ofReal (EarlyLateWagers.earlyWager B π w V j X) + ∂PrefixStage.law B (j + 1)) + + PrefixStage.law B (j + 1) (LateDropBound.partialEvent (B j) π (V j)) ≤ + 4 * StageErrorBudget.error j + first_drop_tail : ∀ j, J ≤ j → + PrefixStage.law B (j + 1) (StoppingTranscript.rankDropTailEvent (B j) π (V j)) ≤ + 2 * StageErrorBudget.error j + high_no_drop : ∀ j, J ≤ j → + PrefixStage.law B j (π.observationMap ⁻¹' H ∩ NoDrop.noDropEvent (B j) π) ≤ + StageErrorBudget.error j + later_low_drop : ∀ j, J ≤ j → ∀ k, j < k → + PrefixStage.law B (j + 1) + (π.observationMap ⁻¹' Hᶜ ∩ LateDropBound.hasDrop (B k) π) ≤ StageErrorBudget.error k + +namespace StageEstimates + +variable {B : ℕ → AffineBlock} {π : ScanRule} {w : List Bool → ℝ} + {V : ℕ → ℕ} {H : Set Cantor} {J : ℕ} + +/-- The stage hypotheses give the paper's `8e_j` late-drop bound under the actual infinite law. -/ +theorem late_bound (h : StageEstimates B π w V H J) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) + (j : ℕ) (hj : J ≤ j) : + BlockProduct.law B hdis (DropEvents.lateEvent B π V j) ≤ 8 * StageErrorBudget.error j := by + have hp : PrefixStage.law B (j + 1) (LateDropBound.partialEvent (B j) π (V j)) ≤ + 4 * StageErrorBudget.error j := + (le_add_of_nonneg_left bot_le).trans (h.early_and_partial j hj) + calc + _ ≤ 4 * StageErrorBudget.error j + 2 * StageErrorBudget.error j + + StageErrorBudget.error j + + ∑' k : {k : ℕ // j < k}, StageErrorBudget.error k.val := + LateDropBound.law_lateEvent_le B hdis π V j H h.measurableH + (4 * StageErrorBudget.error j) (2 * StageErrorBudget.error j) + (StageErrorBudget.error j) StageErrorBudget.error + (h.horizon_avoidance j hj) hp (h.first_drop_tail j hj) + (h.high_no_drop j hj) (h.later_low_drop j hj) + _ = _ := by rw [StageErrorBudget.tail_error]; ring + +/-- Horizon avoidance transfers the early-wager expectation to the actual infinite law. -/ +theorem early_bound (h : StageEstimates B π w V H J) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) + (j : ℕ) (hj : J ≤ j) : + (∫⁻ X, ENNReal.ofReal (EarlyLateWagers.earlyWager B π w V j X) + ∂BlockProduct.law B hdis) ≤ 4 * StageErrorBudget.error j := by + rw [HorizonLaw.lintegral_earlyWager_eq_stage B hdis π w V j (h.horizon_avoidance j hj)] + exact (le_add_of_nonneg_right bot_le).trans (h.early_and_partial j hj) + +/-- The actual Section 5 estimates imply equation (11), including all initial exceptional blocks. -/ +theorem ae_summable_forcedWager (h : StageEstimates B π w V H J) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) : + ∀ᵐ X ∂BlockProduct.law B hdis, Summable (EarlyLateWagers.forcedWager B π w X) := by + exact EarlyLateWagers.ae_summable_forcedWager_of_bounds (BlockProduct.law B hdis) B π w V J + (fun j => 8 * StageErrorBudget.error j) (fun j => 4 * StageErrorBudget.error j) + (StageErrorBudget.tsum_mul_error_lt_top 8 (by norm_num)) + (StageErrorBudget.tsum_mul_error_lt_top 4 (by norm_num)) + (h.late_bound hdis) (h.early_bound hdis) + +end StageEstimates + +/-- Stage estimates for every normalized strategy suffice for almost-sure KL randomness. +The Borel partition and the exceptional block cutoff may depend on the strategy. -/ +theorem ae_kolmogorovLovelandRandom_of_stage_estimates (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) (V : ℕ → ℕ) + (hstage : ∀ s : BettingStrategy, ∃ (H : Set Cantor) (J : ℕ), + StageEstimates B s.normalize.scan s.normalize.capital.wager V H J) : + ∀ᵐ X ∂BlockProduct.law B hdis, KolmogorovLovelandRandom X := by + apply BlockRandomness.ae_kolmogorovLovelandRandom_of_forced_summable B hdis + intro s + obtain ⟨H, J, h⟩ := hstage s + exact h.ae_summable_forcedWager hdis + +/-- Conditional completion of the paper's argument: actual stage estimates and an effective +description cover yield separation. Their simultaneous construction is still required. -/ +theorem exists_separating_of_stage_estimates_and_descriptions (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) (V : ℕ → ℕ) + (hstage : ∀ s : BettingStrategy, ∃ (H : Set Cantor) (J : ℕ), + StageEstimates B s.normalize.scan s.normalize.capital.wager V H J) + {W : ℕ × List Bool × List Bool → Prop} (hW : REPred W) + (hbound : ∀ (n : ℕ) (p : List Bool), + fairCoin (cylinderUnion (fun v => W (n, p, v))) ≤ + (1 / 2 : ℝ≥0∞) ^ (2 * p.length + n + 1)) + (hcover : ∀ n : ℕ, ∃ (j : ℕ) (p : List Bool), + (B j).event ⊆ cylinderUnion (fun v => W (n, p, v))) : + ∃ X : Cantor, KolmogorovLovelandRandom X ∧ ¬MartinLofRandom X := by + apply BlockRandomness.exists_separating_of_description_cover B hdis ?_ hW hbound hcover + intro s + obtain ⟨H, J, h⟩ := hstage s + exact h.ae_summable_forcedWager hdis + +end Klr diff --git a/LeanPool/KLRandomness/StageFiniteCondition.lean b/LeanPool/KLRandomness/StageFiniteCondition.lean new file mode 100644 index 0000000000..b29d965da4 --- /dev/null +++ b/LeanPool/KLRandomness/StageFiniteCondition.lean @@ -0,0 +1,71 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.StageFiniteProbability + +/-! +# Exact conditional sums for arbitrary finite Boolean conditions + +The new syndrome can be tested directly on finite input words before a +certified affine code is reconstructed. This general finite-prefix formula +computes its conditional expectations with exact rational arithmetic. +-/ + +@[expose] public section + +namespace Klr.StageFiniteCondition + +open MeasureTheory ProbabilityTheory RationalComputability + +/-- The inputs whose prefix of the prescribed length passes a Boolean test. -/ +def event (n : ℕ) (p : List Bool → Bool) : Set Cantor := + {X | p (ScanRule.inputPrefix X n) = true} + +theorem measurableSet_event (n : ℕ) (p : List Bool → Bool) : + MeasurableSet (event n p) := by + have hm : Measurable (fun X : Cantor => p (ScanRule.inputPrefix X n)) := by + simpa only [ScanRule.monotone_transcript] using + DropEvents.measurable_transcript_eval ScanRule.monotone n p + exact hm (measurableSet_singleton true) + +/-- A finite conditional sum, also defined when the condition is empty. -/ +def expectation (n : ℕ) (p : List Bool → Bool) (f : List Bool → ℚ) : ℚ := + PoolAdvice.average n (fun s => if p s then f s else 0) / + PoolAdvice.average n (fun s => if p s then 1 else 0) + +theorem computable_expectation {α : Type*} [Primcodable α] + {n : α → ℕ} {p : α → List Bool → Bool} {f : α → List Bool → ℚ} + (hn : Computable n) (hp : Computable₂ p) (hf : Computable₂ f) : + Computable (fun a => expectation (n a) (p a) (f a)) := by + have hnum := PoolAdvice.computable_average (f := fun a s => + _root_.cond (p a s) (f a s) (0 : ℚ)) hn + (Computable.cond hp hf (Computable.const (0 : ℚ))) + have hden := PoolAdvice.computable_average (f := fun a s => + _root_.cond (p a s) (1 : ℚ) 0) hn + (Computable.cond hp (Computable.const (1 : ℚ)) (Computable.const 0)) + exact (primrec_rat_div.to_comp.comp hnum hden).of_eq fun _ => by + simp only [expectation, Bool.cond_eq_ite] + +theorem average_eq_setIntegral (n : ℕ) (p : List Bool → Bool) (f : List Bool → ℚ) : + (PoolAdvice.average n (fun s => if p s then f s else 0) : ℝ) = + ∫ X in event n p, (f (ScanRule.inputPrefix X n) : ℝ) ∂fairCoin := by + rw [PoolAdvice.average_eq_integral, ← integral_indicator (measurableSet_event n p)] + apply integral_congr_ae + filter_upwards [] with X + by_cases h : p (ScanRule.inputPrefix X n) = true <;> simp [event, Set.indicator, h] + +theorem expectation_eq_integral (n : ℕ) (p : List Bool → Bool) (f : List Bool → ℚ) : + (expectation n p f : ℝ) = + ∫ X, (f (ScanRule.inputPrefix X n) : ℝ) ∂cond fairCoin (event n p) := by + rw [expectation, Rat.cast_div, average_eq_setIntegral, average_eq_setIntegral] + simp [ProbabilityTheory.cond, integral_smul_measure, measureReal_def, + ENNReal.toReal_inv, smul_eq_mul, div_eq_mul_inv, mul_comm] + +end Klr.StageFiniteCondition diff --git a/LeanPool/KLRandomness/StageFiniteProbability.lean b/LeanPool/KLRandomness/StageFiniteProbability.lean new file mode 100644 index 0000000000..28b7350eb2 --- /dev/null +++ b/LeanPool/KLRandomness/StageFiniteProbability.lean @@ -0,0 +1,163 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.AffineCodePrefix +public import LeanPool.KLRandomness.PoolAdviceComputable +public import LeanPool.KLRandomness.PoolAdviceMeasure +public import Mathlib.Probability.ConditionalProbability + +/-! +# Exact rational integration under finitely many affine constraints + +The old stage is represented by a finite list of ordinary affine codes. At any +prefix depth covering their widths, conditioning is an exact ratio of two +finite rational sums. The same algorithm works when the codes themselves vary; +in particular it can be used to compare all syndromes of a proposed new block. + +The identities include inconsistent constraints (both the conditional measure +and the rational quotient then vanish). Positivity is needed only when the law +is subsequently used as a probability measure. +-/ + +@[expose] public section + +namespace Klr.StageFiniteProbability + +open MeasureTheory ProbabilityTheory SparseSearch RationalComputability + +/-- The actual simultaneous event represented by a finite list of codes. -/ +def event (cs : List AffineCode.Data) : Set Cantor := + {X | ∀ c ∈ cs, X ∈ AffineCode.event c} + +@[simp] theorem event_nil : event [] = Set.univ := by ext X; simp [event] + +@[simp] theorem event_cons (c : AffineCode.Data) (cs : List AffineCode.Data) : + event (c :: cs) = AffineCode.event c ∩ event cs := by + ext X + simp [event] + +theorem measurableSet_event (cs : List AffineCode.Data) : MeasurableSet (event cs) := by + induction cs with + | nil => simp + | cons c cs ih => simpa only [event_cons] using (AffineCode.measurableSet_event c).inter ih + +/-- The finite-stage law, with all previous affine equations in the header. -/ +noncomputable def law (cs : List AffineCode.Data) : Measure Cantor := + cond fairCoin (event cs) + +/-- Check all old equations on one input prefix. -/ +def accepts (cs : List AffineCode.Data) (s : List Bool) : Bool := + cs.all (fun c => AffineCode.accepts c s) + +theorem computable_accepts : Computable₂ accepts := by + exact computable_list_all Computable.fst + (AffineCode.computable_accepts.comp Computable.snd + (Computable.snd.comp Computable.fst)) + +/-- Covering a code's width is enough; extra input bits do not affect its event. -/ +theorem accepts_code_inputPrefix (c : AffineCode.Data) (n : ℕ) + (hn : AffineCode.width c ≤ n) (X : Cantor) : + AffineCode.accepts c (ScanRule.inputPrefix X n) = true ↔ X ∈ AffineCode.event c := by + constructor + · intro h + exact AffineCode.cylinder_subset_event h (ScanRule.mem_cylinder_inputPrefix X n) + · intro h + apply (AffineCode.accepts_eq_true _ _).mpr + refine ⟨by simpa using hn, ?_⟩ + intro i hi + rw [← (AffineCode.mem_event_iff c X).mp h i hi] + apply AffineCode.parity_congr + intro k hk + dsimp only + rw [ScanRule.getD_inputPrefix X (hk.trans_le hn)] + +theorem accepts_inputPrefix (cs : List AffineCode.Data) (n : ℕ) + (hn : ∀ c ∈ cs, AffineCode.width c ≤ n) (X : Cantor) : + accepts cs (ScanRule.inputPrefix X n) = true ↔ X ∈ event cs := by + simp only [accepts, List.all_eq_true, event, Set.mem_ofPred_eq] + exact forall₂_congr fun c hc => accepts_code_inputPrefix c n (hn c hc) X + +/-- Finite conditional expectation, computed with exact rational arithmetic. -/ +def expectation (cs : List AffineCode.Data) (n : ℕ) (f : List Bool → ℚ) : ℚ := + PoolAdvice.average n (fun s => if accepts cs s then f s else 0) / + PoolAdvice.average n (fun s => if accepts cs s then 1 else 0) + +/-- The finite ratio is uniformly computable in the old constraints, depth, +and every additional parameter of a computable rational integrand. -/ +theorem computable_expectation {α : Type*} [Primcodable α] + {cs : α → List AffineCode.Data} {n : α → ℕ} {f : α → List Bool → ℚ} + (hcs : Computable cs) (hn : Computable n) (hf : Computable₂ f) : + Computable (fun a => expectation (cs a) (n a) (f a)) := by + have ha := computable_accepts.comp (hcs.comp Computable.fst) Computable.snd + have hnum := PoolAdvice.computable_average (f := fun a s => + _root_.cond (accepts (cs a) s) (f a s) (0 : ℚ)) hn + (Computable.cond ha hf (Computable.const (0 : ℚ))) + have hden := PoolAdvice.computable_average (f := fun a s => + _root_.cond (accepts (cs a) s) (1 : ℚ) 0) hn + (Computable.cond ha (Computable.const (1 : ℚ)) (Computable.const 0)) + exact (primrec_rat_div.to_comp.comp hnum hden).of_eq fun _ => by + simp only [expectation, Bool.cond_eq_ite] + +theorem denominator_eq_measureReal (cs : List AffineCode.Data) (n : ℕ) + (hn : ∀ c ∈ cs, AffineCode.width c ≤ n) : + (PoolAdvice.average n (fun s => if accepts cs s then (1 : ℚ) else 0) : ℝ) = + fairCoin.real (event cs) := by + rw [PoolAdvice.average_eq_integral, ← integral_indicator_one (measurableSet_event cs)] + apply integral_congr_ae + filter_upwards [] with X + by_cases hX : X ∈ event cs + · simp [Set.indicator_of_mem hX, (accepts_inputPrefix cs n hn X).mpr hX] + · simp [Set.indicator_of_notMem hX, mt (accepts_inputPrefix cs n hn X).mp hX] + +/-- The executable finite sum is the integral under the actual conditional law. -/ +theorem expectation_eq_integral (cs : List AffineCode.Data) (n : ℕ) + (hn : ∀ c ∈ cs, AffineCode.width c ≤ n) (f : List Bool → ℚ) : + (expectation cs n f : ℝ) = + ∫ X, (f (ScanRule.inputPrefix X n) : ℝ) ∂law cs := by + have hnum : + (PoolAdvice.average n (fun s => if accepts cs s then f s else 0) : ℝ) = + ∫ X in event cs, (f (ScanRule.inputPrefix X n) : ℝ) ∂fairCoin := by + rw [PoolAdvice.average_eq_integral, ← integral_indicator (measurableSet_event cs)] + apply integral_congr_ae + filter_upwards [] with X + by_cases hX : X ∈ event cs + · simp [Set.indicator_of_mem hX, (accepts_inputPrefix cs n hn X).mpr hX] + · simp [Set.indicator_of_notMem hX, mt (accepts_inputPrefix cs n hn X).mp hX] + rw [expectation, Rat.cast_div, hnum, denominator_eq_measureReal cs n hn] + simp [law, ProbabilityTheory.cond, integral_smul_measure, measureReal_def, ENNReal.toReal_inv, + smul_eq_mul, div_eq_mul_inv, mul_comm] + +/-- A Boolean prefix event has an exact rational finite-stage probability. -/ +def probability (cs : List AffineCode.Data) (n : ℕ) (p : List Bool → Bool) : ℚ := + expectation cs n (fun s => if p s then 1 else 0) + +theorem computable_probability {α : Type*} [Primcodable α] + {cs : α → List AffineCode.Data} {n : α → ℕ} {p : α → List Bool → Bool} + (hcs : Computable cs) (hn : Computable n) (hp : Computable₂ p) : + Computable (fun a => probability (cs a) (n a) (p a)) := by + exact (computable_expectation (f := fun a s => _root_.cond (p a s) (1 : ℚ) 0) hcs hn + (Computable.cond hp (Computable.const (1 : ℚ)) (Computable.const 0))).of_eq + fun _ => by simp only [probability, Bool.cond_eq_ite] + +theorem probability_eq_measureReal (cs : List AffineCode.Data) (n : ℕ) + (hn : ∀ c ∈ cs, AffineCode.width c ≤ n) (p : List Bool → Bool) : + (probability cs n p : ℝ) = + (law cs).real {X | p (ScanRule.inputPrefix X n) = true} := by + have hm : Measurable (fun X : Cantor => p (ScanRule.inputPrefix X n)) := by + simpa only [ScanRule.monotone_transcript] using + DropEvents.measurable_transcript_eval ScanRule.monotone n p + have hs : MeasurableSet {X | p (ScanRule.inputPrefix X n) = true} := + hm (measurableSet_singleton true) + rw [probability, expectation_eq_integral cs n hn, ← integral_indicator_one hs] + apply integral_congr_ae + filter_upwards [] with X + by_cases h : p (ScanRule.inputPrefix X n) = true <;> simp [h, Set.indicator] + +end Klr.StageFiniteProbability diff --git a/LeanPool/KLRandomness/StageFiniteScan.lean b/LeanPool/KLRandomness/StageFiniteScan.lean new file mode 100644 index 0000000000..b185a4d958 --- /dev/null +++ b/LeanPool/KLRandomness/StageFiniteScan.lean @@ -0,0 +1,204 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.StageFiniteProbability +public import LeanPool.KLRandomness.HorizonAvoidance + +/-! +# Computable finite-stage statistics for adaptive scans + +At a finite query horizon there are only finitely many possible query +positions, including all adaptive branches. We give a computable bound for +them, simulate the scan on a finite input word, and prove that the exact +rational conditional average is the actual finite-stage expectation. +-/ + +@[expose] public section + +namespace Klr.StageFiniteScan + +open MeasureTheory SparseSearch + +/-- Sum the first `n` values of a natural-number-valued sequence. -/ +def boundedSum (f : ℕ → ℕ) : ℕ → ℕ + | 0 => 0 + | n + 1 => boundedSum f n + f n + +theorem boundedSum_succ_shift (f : ℕ → ℕ) (n : ℕ) : + boundedSum f (n + 1) = f 0 + boundedSum (fun i => f (i + 1)) n := by + induction n with + | zero => simp [boundedSum] + | succ n ih => rw [boundedSum, ih, boundedSum, Nat.add_assoc] + +theorem boundedSum_getD {β : Type*} (f : β → ℕ) (l : List β) (d : β) : + boundedSum (fun i => f (l.getD i d)) l.length = (l.map f).sum := by + induction l with + | nil => rfl + | cons b l ih => + rw [List.length_cons, boundedSum_succ_shift] + simpa only [List.getD_cons_zero, List.getD_cons_succ, List.map_cons, List.sum_cons] using + congrArg (fun q => f b + q) ih + +theorem computable_boundedSum {α : Type*} [Primcodable α] {f : α → ℕ → ℕ} + (hf : Computable₂ f) : Computable (fun a : α × ℕ => boundedSum (f a.1) a.2) := by + have hs : Computable (fun p : (α × ℕ) × (ℕ × ℕ) => + p.2.2 + f p.1.1 p.2.1) := Primrec.nat_add.to_comp.comp + (Computable.snd.comp Computable.snd) + (hf.comp (Computable.fst.comp Computable.fst) (Computable.fst.comp Computable.snd)) + apply (Computable.nat_rec Computable.snd (Computable.const 0) hs.to₂).of_eq + intro a + induction a.2 with + | zero => rfl + | succ n ih => + simpa only [boundedSum, Nat.rec_add_one] using congrArg (fun q => q + f a.1 n) ih + +theorem computable_list_sum {α β : Type*} [Primcodable α] [Primcodable β] + [Inhabited β] {l : α → List β} {f : α → β → ℕ} + (hl : Computable l) (hf : Computable₂ f) : + Computable (fun a => ((l a).map (f a)).sum) := by + have hg := (Primrec.list_getD default).to_comp.comp + (hl.comp Computable.fst) Computable.snd + have hc := (computable_boundedSum + (f := fun a i => f a ((l a).getD i default)) (hf.comp Computable.fst hg)).comp + (Computable.id.pair (Computable.list_length.comp hl)) + exact hc.of_eq fun a => boundedSum_getD (f a) (l a) default + +/-- A deliberately generous bound, obtained by summing over every branch. -/ +def branchBound (π : ScanRule) (V : ℕ) : ℕ := + ((List.range V).map (fun t => ((words t).map (fun v => π.query v + 1)).sum)).sum + +theorem computable_branchBound (π : ScanRule) : Computable (branchBound π) := by + have hi : Computable (fun t => ((words t).map (fun v => π.query v + 1)).sum) := + computable_list_sum computable_words + ((Primrec.succ.to_comp.comp π.computable_query).comp Computable.snd) + exact computable_list_sum Primrec.list_range.to_comp (hi.comp Computable.snd) + +theorem query_lt_branchBound (π : ScanRule) (V : ℕ) (v : List Bool) + (hv : v.length < V) : π.query v < branchBound π V := by + have hin : π.query v + 1 ≤ ((words v.length).map (fun w => π.query w + 1)).sum := + List.le_sum_of_mem + (List.mem_map.mpr ⟨v, (mem_words_iff _ _).mpr rfl, rfl⟩) + have hout : ((words v.length).map (fun w => π.query w + 1)).sum ≤ branchBound π V := + List.le_sum_of_mem + (List.mem_map.mpr ⟨v.length, List.mem_range.mpr hv, rfl⟩) + exact Nat.lt_of_succ_le (hin.trans hout) + +/-- An input depth covering both the old constraints and every scan branch. -/ +def depth (cs : List AffineCode.Data) (π : ScanRule) (V : ℕ) : ℕ := + (cs.map AffineCode.width).sum + branchBound π V + +theorem width_le_depth {cs : List AffineCode.Data} (π : ScanRule) (V : ℕ) + {c : AffineCode.Data} (hc : c ∈ cs) : AffineCode.width c ≤ depth cs π V := by + exact (List.le_sum_of_mem + (List.mem_map.mpr ⟨c, hc, rfl⟩)).trans (Nat.le_add_right _ _) + +theorem query_lt_depth (cs : List AffineCode.Data) (π : ScanRule) (V : ℕ) + (v : List Bool) (hv : v.length < V) : π.query v < depth cs π V := + (query_lt_branchBound π V v hv).trans_le (Nat.le_add_left _ _) + +theorem computable_depth (π : ScanRule) : + Computable (fun p : List AffineCode.Data × ℕ => depth p.1 π p.2) := by + have hw := computable_list_sum (l := fun p : List AffineCode.Data × ℕ => p.1) + (f := fun _ c => AffineCode.width c) Computable.fst + (AffineCode.computable_width.comp Computable.snd) + exact Primrec.nat_add.to_comp.comp hw ((computable_branchBound π).comp Computable.snd) + +/-- Simulate a finite adaptive scan, zero-filling outside the supplied word. -/ +def run (π : ScanRule) (s : List Bool) (t : ℕ) : List Bool := + π.transcript (fun n => s.getD n false) t + +theorem computable_run (π : ScanRule) : Computable₂ (run π) := by + have hprev : Computable (fun p : (List Bool × ℕ) × (ℕ × List Bool) => p.2.2) := + Computable.snd.comp Computable.snd + have hs : Computable (fun p : (List Bool × ℕ) × (ℕ × List Bool) => p.1.1) := + Computable.fst.comp Computable.fst + have hb := (Primrec.list_getD false).to_comp.comp hs (π.computable_query.comp hprev) + have hstep := Computable.list_append.comp hprev + (Primrec.list_cons.to_comp.comp hb (Computable.const [])) + apply (Computable.nat_rec Computable.snd (Computable.const []) hstep.to₂).of_eq + intro p + induction p.2 with + | zero => rfl + | succ t ih => + simpa only [run, ScanRule.transcript_succ, Nat.rec_add_one] using + congrArg (fun v => v ++ [p.1.getD (π.query v) false]) ih + +/-- The all-branch bound proves simulation correct on every input, with no +almost-everywhere or termination exception. -/ +theorem run_inputPrefix_of_bound (π : ScanRule) (V n : ℕ) + (hn : ∀ v : List Bool, v.length < V → π.query v < n) + (X : Cantor) {t : ℕ} (ht : t ≤ V) : + run π (ScanRule.inputPrefix X n) t = π.transcript X t := by + induction t with + | zero => rfl + | succ t ih => + have he := ih (by omega) + change run π (ScanRule.inputPrefix X n) t ++ + [(ScanRule.inputPrefix X n).getD (π.query (run π (ScanRule.inputPrefix X n) t)) false] = _ + rw [he, ScanRule.getD_inputPrefix X + (hn (π.transcript X t) (by simpa using Nat.lt_of_succ_le ht))] + rfl + +/-- Specialization to the explicit computable depth. -/ +theorem run_inputPrefix (cs : List AffineCode.Data) (π : ScanRule) (V : ℕ) + (X : Cantor) {t : ℕ} (ht : t ≤ V) : + run π (ScanRule.inputPrefix X (depth cs π V)) t = π.transcript X t := by + exact run_inputPrefix_of_bound π V _ (query_lt_depth cs π V) X ht + +/-- Exact rational expectation of a statistic on the length-`V` transcript. -/ +def expectation (cs : List AffineCode.Data) (π : ScanRule) (V : ℕ) + (f : List Bool → ℚ) : ℚ := + StageFiniteProbability.expectation cs (depth cs π V) (fun s => f (run π s V)) + +theorem computable_expectation (π : ScanRule) {α : Type*} [Primcodable α] + {cs : α → List AffineCode.Data} {V : α → ℕ} {f : α → List Bool → ℚ} + (hcs : Computable cs) (hV : Computable V) (hf : Computable₂ f) : + Computable (fun a => expectation (cs a) π (V a) (f a)) := by + have hn := (computable_depth π).comp (hcs.pair hV) + have hr := (computable_run π).comp Computable.snd (hV.comp Computable.fst) + exact StageFiniteProbability.computable_expectation hcs hn (hf.comp Computable.fst hr) + +/-- The finite algorithm computes the actual conditional expectation. -/ +theorem expectation_eq_integral (cs : List AffineCode.Data) (π : ScanRule) (V : ℕ) + (f : List Bool → ℚ) : + (expectation cs π V f : ℝ) = + ∫ X, (f (π.transcript X V) : ℝ) ∂StageFiniteProbability.law cs := by + rw [expectation, StageFiniteProbability.expectation_eq_integral cs _ + (fun _ hc => width_le_depth π V hc)] + apply integral_congr_ae + exact Filter.Eventually.of_forall fun X => by + dsimp only + rw [run_inputPrefix cs π V X le_rfl] + +/-- Exact finite-horizon event probability, uniformly in the affine codes. -/ +def probability (cs : List AffineCode.Data) (π : ScanRule) (V : ℕ) + (p : List Bool → Bool) : ℚ := + expectation cs π V (fun v => if p v then 1 else 0) + +theorem computable_probability (π : ScanRule) {α : Type*} [Primcodable α] + {cs : α → List AffineCode.Data} {V : α → ℕ} {p : α → List Bool → Bool} + (hcs : Computable cs) (hV : Computable V) (hp : Computable₂ p) : + Computable (fun a => probability (cs a) π (V a) (p a)) := by + exact (computable_expectation π (f := fun a s => cond (p a s) (1 : ℚ) 0) hcs hV + (Computable.cond hp (Computable.const (1 : ℚ)) (Computable.const 0))).of_eq + fun _ => by simp only [probability, Bool.cond_eq_ite] + +theorem probability_eq_measureReal (cs : List AffineCode.Data) (π : ScanRule) (V : ℕ) + (p : List Bool → Bool) : + (probability cs π V p : ℝ) = + (StageFiniteProbability.law cs).real {X | p (π.transcript X V) = true} := by + have hs : MeasurableSet {X | p (π.transcript X V) = true} := + (DropEvents.measurable_transcript_eval π V p) (measurableSet_singleton true) + rw [probability, expectation_eq_integral, ← integral_indicator_one hs] + apply integral_congr_ae + filter_upwards [] with X + by_cases h : p (π.transcript X V) = true <;> simp [h, Set.indicator] + +end Klr.StageFiniteScan diff --git a/LeanPool/KLRandomness/StageFiniteWager.lean b/LeanPool/KLRandomness/StageFiniteWager.lean new file mode 100644 index 0000000000..c32dd9dae5 --- /dev/null +++ b/LeanPool/KLRandomness/StageFiniteWager.lean @@ -0,0 +1,230 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.StageWeights +public import LeanPool.KLRandomness.StageCandidate +public import LeanPool.KLRandomness.PoolAdviceComputable +import Mathlib.Tactic.NormNum +import Mathlib.Tactic.Positivity + +/-! +# Computable rational support wagers at a finite horizon + +The analytic support sum is evaluated on a finite answer transcript. Its +executable form uses the candidate's Boolean mask and the actual finite pool +list, so no support-membership oracle is supplied to the stage algorithm. +The rational signed wagers are exactly those of the normalized strategies. +-/ + +@[expose] public section + +namespace Klr.StageFiniteWager + +open MeasureTheory RationalComputability +open scoped BigOperators + +/-- The signed rational wager underlying the actual normalized strategy. -/ +noncomputable def normalizedWager (s : BettingStrategy) : List Bool → ℚ := + (CapitalApproximation.ofComputable s.capital s.computable_capital).reserve.normalizedFraction + +theorem computable_normalizedWager (s : BettingStrategy) : Computable (normalizedWager s) := by + let R := (CapitalApproximation.ofComputable s.capital s.computable_capital).reserve + have hv : Computable R.variation := + Computable.fst.comp (Computable.snd.comp R.computable_normalizationAccount) + exact (primrec_rat_div.to_comp.comp R.computable_wager + (primrec_rat_mul.to_comp.comp (Computable.const 2) + (primrec_rat_add.to_comp.comp (Computable.const 1) hv))).of_eq fun _ => rfl + +theorem cast_normalizedWager (s : BettingStrategy) (v : List Bool) : + (normalizedWager s v : ℝ) = s.normalize.capital.wager v := + (ReservedRationalCapital.normalizedCapital_wager _ v).symm + +theorem normalizedWager_abs_le_half (s : BettingStrategy) (v : List Bool) : + |(normalizedWager s v : ℝ)| ≤ 1 / 2 := by + rw [cast_normalizedWager] + exact s.normalize_wager_abs_le_half v + +/-- Total absolute wager placed inside a support while reading a finite +answer transcript. The summation uses only proper prefixes of that transcript. -/ +def truncated (π : ScanRule) (h : List Bool → ℚ) (S : Finset ℕ) (v : List Bool) : ℚ := + ∑ t ∈ Finset.range v.length, if π.query (v.take t) ∈ S then |h (v.take t)| else 0 + +theorem truncated_nonneg (π : ScanRule) (h : List Bool → ℚ) (S : Finset ℕ) (v : List Bool) : + 0 ≤ truncated π h S v := + Finset.sum_nonneg fun t _ => by split_ifs <;> positivity + +theorem cast_truncated_nonneg (π : ScanRule) (h : List Bool → ℚ) + (S : Finset ℕ) (v : List Bool) : 0 ≤ (truncated π h S v : ℝ) := + Rat.cast_nonneg.mpr (truncated_nonneg π h S v) + +/-- Exact agreement with the actual wagers on the first `V` adaptive queries. -/ +theorem cast_truncated_transcript (π : ScanRule) (h : List Bool → ℚ) + (S : Finset ℕ) (X : Cantor) (V : ℕ) : + (truncated π h S (π.transcript X V) : ℝ) = + ∑ t ∈ Finset.range V, + if π.query (π.transcript X t) ∈ S then |(h (π.transcript X t) : ℝ)| else 0 := by + unfold truncated + push_cast + rw [π.length_transcript] + apply Finset.sum_congr rfl + intro t ht + rw [π.transcript_take X (Finset.mem_range.mp ht).le] + split_ifs <;> simp + +/-- The real finite-horizon objective is measurable on actual inputs. -/ +theorem measurable_truncated (π : ScanRule) (h : List Bool → ℚ) (S : Finset ℕ) (V : ℕ) : + Measurable (fun X => (truncated π h S (π.transcript X V) : ℝ)) := + DropEvents.measurable_transcript_eval π V (fun v => (truncated π h S v : ℝ)) + +theorem truncated_transcript_le_half_horizon (π : ScanRule) (h : List Bool → ℚ) + (S : Finset ℕ) (X : Cantor) (V : ℕ) + (hh : ∀ v, |(h v : ℝ)| ≤ 1 / 2) : + (truncated π h S (π.transcript X V) : ℝ) ≤ (V : ℝ) / 2 := by + rw [cast_truncated_transcript] + calc + _ ≤ ∑ _t ∈ Finset.range V, (1 / 2 : ℝ) := by + apply Finset.sum_le_sum + intro t _ + split_ifs + · exact hh _ + · norm_num + _ = _ := by simp [div_eq_mul_inv] + +/-- Truncation is bounded by the all-time support total used in candidate selection. -/ +theorem truncated_transcript_le_supportWager (π : ScanRule) (h : List Bool → ℚ) + (S : Finset ℕ) (X : Cantor) (V : ℕ) : + (truncated π h S (π.transcript X V) : ℝ) ≤ + StageWeights.supportWager π (fun v => (h v : ℝ)) S X := by + rw [cast_truncated_transcript] + exact StageWeights.partial_supportWager_le π (fun v => (h v : ℝ)) S X V + +/-- The finite rational objective dominates the actual early forced wagers. -/ +theorem earlyWager_le_truncated (B : ℕ → AffineBlock) (π : ScanRule) + (h : List Bool → ℚ) (V : ℕ → ℕ) (j : ℕ) (X : Cantor) : + EarlyLateWagers.earlyWager B π (fun v => (h v : ℝ)) V j X ≤ + (truncated π h (B j).support (π.transcript X (V j)) : ℝ) := by + rw [cast_truncated_transcript] + exact StageWeights.earlyWager_le_partial_supportWager B π (fun v => (h v : ℝ)) V j X + +/-- Executable form with an arbitrary Boolean support test. -/ +def truncatedWith (q : List Bool → ℕ) (h : List Bool → ℚ) + (selected : ℕ → Bool) (v : List Bool) : ℚ := + ((List.range v.length).map + (fun t => if selected (q (v.take t)) then |h (v.take t)| else 0)).sum + +theorem truncatedWith_eq_truncated (π : ScanRule) (h : List Bool → ℚ) + (selected : ℕ → Bool) (S : Finset ℕ) + (hs : ∀ a, selected a = true ↔ a ∈ S) (v : List Bool) : + truncatedWith π.query h selected v = truncated π h S v := by + rw [truncatedWith, ← List.sum_toFinset _ (List.nodup_range (n := v.length))] + simp only [List.toFinset_range, truncated, hs] + +/-- All finite parameters may vary computably, including the support test +and the wager function. No global effective enumeration of all scans is assumed. -/ +theorem computable_truncatedWith {α : Type*} [Primcodable α] + {q : α → List Bool → ℕ} {h : α → List Bool → ℚ} + {selected : α → ℕ → Bool} {v : α → List Bool} + (hq : Computable₂ q) (hh : Computable₂ h) (hs : Computable₂ selected) + (hv : Computable v) : + Computable (fun a => truncatedWith (q a) (h a) (selected a) (v a)) := by + have hp : Computable (fun p : α × ℕ => (v p.1).take p.2) := + Primrec.list_take.to_comp.comp Computable.snd (hv.comp Computable.fst) + have hg : Computable (fun p : α × ℕ => selected p.1 (q p.1 ((v p.1).take p.2))) := + hs.comp Computable.fst (hq.comp Computable.fst hp) + have hw : Computable (fun p : α × ℕ => |h p.1 ((v p.1).take p.2)|) := + PoolAdvice.computable_rat_abs.comp (hh.comp Computable.fst hp) + exact (PoolAdvice.computable_list_sum + (l := fun a => List.range (v a).length) + (f := fun a t => _root_.cond (selected a (q a ((v a).take t))) |h a ((v a).take t)| 0) + (Primrec.list_range.to_comp.comp (Computable.list_length.comp hv)) + (Computable.cond hg hw (Computable.const (0 : ℚ)))).of_eq fun _ => by + simp only [truncatedWith, Bool.cond_eq_ite] + +/-- Decide whether an actual input position lies in the candidate support, +using only the finite pool and the executable Boolean mask. -/ +def selected (G : List ℕ) (a : SparseListSearch.Entry) (n : ℕ) : Bool := + (List.range G.length).any + (fun j => a.1.getD j false && decide (G.getD j 0 = n)) + +theorem selected_eq_true (G : List ℕ) (a : SparseListSearch.Entry) (n : ℕ) : + selected G a n = true ↔ + n ∈ (SparseListWeights.support G.length a).image G.get := by + rw [selected, List.any_eq_true] + constructor + · rintro ⟨j, hj, h⟩ + have hj' := List.mem_range.mp hj + simp only [Bool.and_eq_true] at h + obtain ⟨hm, hn⟩ := h + refine Finset.mem_image.mpr ⟨⟨j, hj'⟩, ?_, ?_⟩ + · exact (SparseListCode.mem_maskSet G.length a.1 ⟨j, hj'⟩).mpr hm + · exact (List.getD_eq_get G 0 ⟨j, hj'⟩).symm.trans (of_decide_eq_true hn) + · intro hn + obtain ⟨j, hj, hjn⟩ := Finset.mem_image.mp hn + refine ⟨j.val, List.mem_range.mpr j.isLt, ?_⟩ + simp only [Bool.and_eq_true] + constructor + · exact (SparseListCode.mem_maskSet G.length a.1 j).mp hj + · apply decide_eq_true_eq.mpr + exact (List.getD_eq_get G 0 j).trans hjn + +theorem computable_selected {α : Type*} [Primcodable α] + {G : α → List ℕ} {a : α → SparseListSearch.Entry} {n : α → ℕ} + (hG : Computable G) (ha : Computable a) (hn : Computable n) : + Computable (fun p => selected (G p) (a p) (n p)) := by + have hm := (Primrec.list_getD false).to_comp.comp + (Computable.fst.comp (ha.comp Computable.fst)) Computable.snd + have hg := (Primrec.list_getD 0).to_comp.comp (hG.comp Computable.fst) Computable.snd + have he := Primrec.eq.decide.to_comp.comp hg (hn.comp Computable.fst) + exact SparseSearch.computable_list_any + (Primrec.list_range.to_comp.comp (Computable.list_length.comp hG)) + (Primrec.and.to_comp.comp hm he) + +/-- The finite rational cost evaluated directly from the actual pool and candidate code. -/ +def truncatedCandidate (π : ScanRule) (h : List Bool → ℚ) + (G : List ℕ) (a : SparseListSearch.Entry) (v : List Bool) : ℚ := + truncatedWith π.query h (selected G a) v + +theorem truncatedCandidate_eq_truncated (π : ScanRule) (h : List Bool → ℚ) + (G : List ℕ) (a : SparseListSearch.Entry) (v : List Bool) : + truncatedCandidate π h G a v = + truncated π h ((SparseListWeights.support G.length a).image G.get) v := + truncatedWith_eq_truncated π h (selected G a) _ (selected_eq_true G a) v + +theorem computable_truncatedCandidate (π : ScanRule) (h : List Bool → ℚ) + (hh : Computable h) {α : Type*} [Primcodable α] + {G : α → List ℕ} {a : α → SparseListSearch.Entry} {v : α → List Bool} + (hG : Computable G) (ha : Computable a) (hv : Computable v) : + Computable (fun p => truncatedCandidate π h (G p) (a p) (v p)) := + computable_truncatedWith (π.computable_query.comp Computable.snd) + (hh.comp Computable.snd) + (computable_selected (hG.comp Computable.fst) (ha.comp Computable.fst) Computable.snd) + hv + +/-- The executable candidate evaluation is exactly the finite cost on its +embedded affine block, independently of the block's syndrome. -/ +theorem truncatedCandidate_eq_block (π : ScanRule) (h : List Bool → ℚ) + (G : List ℕ) (hG : G.Nodup) {m r : ℕ} (a : SparseListSearch.Entry) + (ha : SparseListSearch.GoodEntry G.length m r a) (y : Fin r → ZMod 2) + (v : List Bool) : + truncatedCandidate π h G a v = + truncated π h (StageCandidate.block G.get hG.injective_get a ha y).support v := + truncatedCandidate_eq_truncated π h G a v + +/-- The actual normalized rational wager needs no extra effectivity premise. -/ +theorem computable_normalized_truncatedCandidate (s : BettingStrategy) + {α : Type*} [Primcodable α] + {G : α → List ℕ} {a : α → SparseListSearch.Entry} {v : α → List Bool} + (hG : Computable G) (ha : Computable a) (hv : Computable v) : + Computable (fun p => + truncatedCandidate s.normalize.scan (normalizedWager s) (G p) (a p) (v p)) := + computable_truncatedCandidate s.normalize.scan (normalizedWager s) + (computable_normalizedWager s) hG ha hv + +end Klr.StageFiniteWager diff --git a/LeanPool/KLRandomness/StageHorizon.lean b/LeanPool/KLRandomness/StageHorizon.lean new file mode 100644 index 0000000000..c4814d227e --- /dev/null +++ b/LeanPool/KLRandomness/StageHorizon.lean @@ -0,0 +1,144 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import Mathlib.Algebra.Order.Archimedean.Real.Basic +public import Mathlib.Topology.Instances.Real.Lemmas +public import Mathlib.Data.Rat.Floor +public import Mathlib.Algebra.Order.Floor.Semiring +public import Mathlib.Basic.Real.Basic +public import Mathlib.Topology.Order.Basic +import Mathlib.Tactic.Linarith + +/-! +# A horizon from bounded integer advice + +The stage construction has two rational finite-horizon quantities: the mass +of partial remaining ranks, and the mass of first drops already seen. Their +limits need not be computable. Only one bounded integer locating the second +limit is supplied as advice; the horizon itself is found by a finite rational +test. The companion file `StageHorizonComputable` implements that search. + +The subtraction in the test is rational subtraction. In particular, advice +zero gives the negative threshold `-error`, which is necessary when the total +mass of first drops is zero. +-/ + +@[expose] public section + +namespace Klr.StageHorizon + +open Filter +open scoped Topology + +/-- The two strict rational inequalities checked at a proposed horizon. -/ +def Accepted (error : ℚ) (u v : ℕ → ℚ) (advice horizon : ℕ) : Prop := + u horizon < 3 * error ∧ ((advice : ℚ) - 1) * error < v horizon + +/-- The stage-dependent bound for the integer advice. It is independent of +the trial rank, candidate support, and horizon. -/ +def adviceBound (error : ℚ) (protectedCount : ℕ) : ℕ := + ⌊(protectedCount : ℚ) / error⌋₊ + +/-- The integer advice places the limiting first-drop mass in an interval +of width `error`. This assertion makes no computability claim about the limit. -/ +def Quantized (error : ℚ) (limit : ℝ) (advice : ℕ) : Prop := + (advice : ℝ) * (error : ℝ) ≤ limit ∧ + limit < ((advice : ℝ) + 1) * (error : ℝ) + +theorem zero_advice_threshold (error : ℚ) : + (((0 : ℕ) : ℚ) - 1) * error = -error := by + simp + +/-- The usual floor choice gives advice bounded entirely by the stage data. -/ +theorem exists_bounded_quantized {error : ℚ} (herror : 0 < error) + {limit : ℝ} (hlimit : 0 ≤ limit) {protectedCount : ℕ} + (hbound : limit ≤ protectedCount) : + ∃ advice, advice ≤ adviceBound error protectedCount ∧ + Quantized error limit advice := by + have he : (0 : ℝ) < error := by exact_mod_cast herror + let advice : ℕ := ⌊limit / (error : ℝ)⌋₊ + have hlo : (advice : ℝ) * (error : ℝ) ≤ limit := + (le_div_iff₀ he).mp (Nat.floor_le (div_nonneg hlimit he.le)) + have hhi : limit < ((advice : ℝ) + 1) * (error : ℝ) := + (div_lt_iff₀ he).mp (Nat.lt_floor_add_one (limit / (error : ℝ))) + refine ⟨advice, ?_, hlo, hhi⟩ + apply Nat.le_floor + apply (le_div_iff₀ herror).mpr + exact_mod_cast hlo.trans hbound + +/-- The lower endpoint of the advice interval is strictly above the rational +search threshold, including when the advice is zero. -/ +theorem threshold_lt_limit {error : ℚ} (herror : 0 < error) + {limit : ℝ} {advice : ℕ} (hquantized : Quantized error limit advice) : + ((((advice : ℚ) - 1) * error : ℚ) : ℝ) < limit := by + have he : (0 : ℝ) < error := by exact_mod_cast herror + push_cast + have hlo := hquantized.1 + nlinarith + +/-- Every accepted horizon has first-drop tail mass below twice the error. +This uses only the upper endpoint of the advice interval, not a modulus of +convergence for the first-drop probabilities. -/ +theorem tail_lt_of_accepted {error : ℚ} {limit : ℝ} {advice horizon : ℕ} + {u v : ℕ → ℚ} (hquantized : Quantized error limit advice) + (haccepted : Accepted error u v advice horizon) : + limit - (v horizon : ℝ) < 2 * (error : ℝ) := by + have hv : ((advice : ℝ) - 1) * (error : ℝ) < (v horizon : ℝ) := by + exact_mod_cast haccepted.2 + have hhi := hquantized.2 + nlinarith + +/-- Convergence supplies accepted horizons eventually once both limiting +values lie strictly inside the acceptance inequalities. -/ +theorem eventually_accepted_of_tendsto {error : ℚ} {u v : ℕ → ℚ} + {uLimit vLimit : ℝ} {advice : ℕ} + (hu : Tendsto (fun n => (u n : ℝ)) atTop (𝓝 uLimit)) + (hv : Tendsto (fun n => (v n : ℝ)) atTop (𝓝 vLimit)) + (huLimit : uLimit < 3 * (error : ℝ)) + (hvLimit : ((((advice : ℚ) - 1) * error : ℚ) : ℝ) < vLimit) : + ∀ᶠ horizon in atTop, Accepted error u v advice horizon := by + have hu' := (tendsto_order.mp hu).2 _ huLimit + have hv' := (tendsto_order.mp hv).1 _ hvLimit + filter_upwards [hu', hv'] with horizon huH hvH + exact ⟨by exact_mod_cast huH, by exact_mod_cast hvH⟩ + +/-- Quantized advice and the partial-rank limit bound imply eventual +acceptance. A non-strict `2 * error` bound is sufficient. -/ +theorem eventually_accepted_of_quantized {error : ℚ} (herror : 0 < error) + {u v : ℕ → ℚ} {uLimit vLimit : ℝ} {advice : ℕ} + (hu : Tendsto (fun n => (u n : ℝ)) atTop (𝓝 uLimit)) + (hv : Tendsto (fun n => (v n : ℝ)) atTop (𝓝 vLimit)) + (huLimit : uLimit ≤ 2 * (error : ℝ)) + (hquantized : Quantized error vLimit advice) : + ∀ᶠ horizon in atTop, Accepted error u v advice horizon := by + have he : (0 : ℝ) < error := by exact_mod_cast herror + exact eventually_accepted_of_tendsto hu hv (by linarith) + (threshold_lt_limit herror hquantized) + +/-- A bounded choice of advice admits a finite rational search and certifies +the tail bound at every horizon accepted by that search. -/ +theorem exists_bounded_advice {error : ℚ} (herror : 0 < error) + {u v : ℕ → ℚ} {uLimit vLimit : ℝ} {protectedCount : ℕ} + (hu : Tendsto (fun n => (u n : ℝ)) atTop (𝓝 uLimit)) + (hv : Tendsto (fun n => (v n : ℝ)) atTop (𝓝 vLimit)) + (huLimit : uLimit ≤ 2 * (error : ℝ)) (hvLimit : 0 ≤ vLimit) + (hbound : vLimit ≤ protectedCount) : + ∃ advice, advice ≤ adviceBound error protectedCount ∧ + Quantized error vLimit advice ∧ + (∀ᶠ horizon in atTop, Accepted error u v advice horizon) ∧ + ∀ horizon, Accepted error u v advice horizon → + vLimit - (v horizon : ℝ) < 2 * (error : ℝ) := by + obtain ⟨advice, hadvice, hquantized⟩ := + exists_bounded_quantized herror hvLimit hbound + exact ⟨advice, hadvice, hquantized, + eventually_accepted_of_quantized herror hu hv huLimit hquantized, + fun _ hh => tail_lt_of_accepted hquantized hh⟩ + +end Klr.StageHorizon diff --git a/LeanPool/KLRandomness/StageHorizonChoice.lean b/LeanPool/KLRandomness/StageHorizonChoice.lean new file mode 100644 index 0000000000..5266dee01f --- /dev/null +++ b/LeanPool/KLRandomness/StageHorizonChoice.lean @@ -0,0 +1,201 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.StageFiniteWager +public import LeanPool.KLRandomness.StageSyndrome +public import LeanPool.KLRandomness.StageRankLimitMeasure +import Mathlib.Tactic.Linarith +import Mathlib.Tactic.NormNum + +/-! +# Choosing a syndrome at the reconstructed horizon + +The objective averages the actual truncated support wagers and partial-rank +indicators of all protected strategies. It depends only on the finite +horizon transcripts, so its conditional expectations can be computed by the +finite stage interpreter. Uniform syndrome averaging shows that every exact +minimizer meets the simultaneous early-wager bound. +-/ + +@[expose] public section + +noncomputable section + +namespace Klr.StageHorizonChoice + +open MeasureTheory ProbabilityTheory AffineBlock StageSyndrome +open scoped BigOperators ENNReal + +/-- The actual next-stage law for a chosen syndrome. -/ +def law {κ : Type*} (old : κ → AffineBlock) (B : AffineBlock) + (y : Fin B.rank → ZMod 2) : Measure Cantor := + cond (finiteStageLaw old) (withSyndrome B y).event + +instance {κ : Type*} (old : κ → AffineBlock) (B : AffineBlock) + (y : Fin B.rank → ZMod 2) : IsFiniteMeasure (law old B y) := by + unfold law + infer_instance + +@[simp] +theorem remainingRank_withSyndrome (B : AffineBlock) (y : Fin B.rank → ZMod 2) + (π : ScanRule) (v : List Bool) : + (withSyndrome B y).remainingRank π v = B.remainingRank π v := rfl + +@[simp] +theorem partialEvent_withSyndrome (B : AffineBlock) (y : Fin B.rank → ZMod 2) + (π : ScanRule) (V : ℕ) : + LateDropBound.partialEvent (withSyndrome B y) π V = LateDropBound.partialEvent B π V := rfl + +@[simp] +theorem rankDropTailEvent_withSyndrome (B : AffineBlock) (y : Fin B.rank → ZMod 2) + (π : ScanRule) (V : ℕ) : + StoppingTranscript.rankDropTailEvent (withSyndrome B y) π V = + StoppingTranscript.rankDropTailEvent B π V := rfl + +@[simp] +theorem noDropEvent_withSyndrome (B : AffineBlock) (y : Fin B.rank → ZMod 2) + (π : ScanRule) : + NoDrop.noDropEvent (withSyndrome B y) π = NoDrop.noDropEvent B π := rfl + +@[simp] +theorem hasDrop_withSyndrome (B : AffineBlock) (y : Fin B.rank → ZMod 2) + (π : ScanRule) : + LateDropBound.hasDrop (withSyndrome B y) π = LateDropBound.hasDrop B π := rfl + +/-- Bounded wager fractions make the all-time finite-support cost integrable +under every finite measure. Freshness leaves at most one wager per position. -/ +theorem integrable_supportWager_of_half_bound (μ : Measure Cantor) [IsFiniteMeasure μ] + (π : ScanRule) (h : List Bool → ℚ) (S : Finset ℕ) + (hh : ∀ v, |(h v : ℝ)| ≤ (1 / 2 : ℝ)) : + Integrable (StageWeights.supportWager π (fun v => (h v : ℝ)) S) μ := by + classical + apply Integrable.of_bound (StageWeights.measurable_supportWager π _ S).aestronglyMeasurable + ((S.card : ℝ) / 2) + apply Filter.Eventually.of_forall + intro X + rw [Real.norm_eq_abs, abs_of_nonneg (StageWeights.supportWager_nonneg π _ S X)] + calc + StageWeights.supportWager π (fun v => (h v : ℝ)) S X ≤ + ∑ _a ∈ S, (1 / 2 : ℝ) := by + apply Finset.sum_le_sum + intro a _ + by_cases ha : ∃ t, π.query (π.transcript X t) = a + · obtain ⟨t, rfl⟩ := ha + rw [StageWeights.wagerAt_eq_of_query] + exact hh _ + · rw [StageWeights.wagerAt_eq_zero_of_not_queried π _ a X (by simpa using ha)] + norm_num + _ = _ := by simp [div_eq_mul_inv] + +/-- The rational finite-horizon wager statistic is integrable under every +finite input law. -/ +theorem integrable_truncated (μ : Measure Cantor) [IsFiniteMeasure μ] + (π : ScanRule) (h : List Bool → ℚ) (S : Finset ℕ) (V : ℕ) + (hh : ∀ v, |(h v : ℝ)| ≤ (1 / 2 : ℝ)) : + Integrable (fun X => (StageFiniteWager.truncated π h S (π.transcript X V) : ℝ)) μ := by + apply Integrable.of_bound (StageFiniteWager.measurable_truncated π h S V).aestronglyMeasurable + ((V : ℝ) / 2) + apply Filter.Eventually.of_forall + intro X + rw [Real.norm_eq_abs, abs_of_nonneg] + · exact StageFiniteWager.truncated_transcript_le_half_horizon π h S X V hh + · exact_mod_cast StageFiniteWager.truncated_nonneg π h S (π.transcript X V) + +variable {ι : Type*} [Fintype ι] + +/-- One finite-transcript objective for all protected strategies. It uses +truncated support wagers so that exact rational evaluation is possible. -/ +def objective (B : AffineBlock) (π : ι → ScanRule) (h : ι → List Bool → ℚ) + (V : ℕ) (X : Cantor) : ℝ := + ∑ i, ((StageFiniteWager.truncated (π i) (h i) B.support ((π i).transcript X V) : ℝ) + + (LateDropBound.partialEvent B (π i) V).indicator (fun _ => (1 : ℝ)) X) + +@[simp] +theorem objective_withSyndrome (B : AffineBlock) (y : Fin B.rank → ZMod 2) + (π : ι → ScanRule) (h : ι → List Bool → ℚ) (V : ℕ) : + objective (withSyndrome B y) π h V = objective B π h V := rfl + +theorem integrable_objective (μ : Measure Cantor) [IsFiniteMeasure μ] + (B : AffineBlock) (π : ι → ScanRule) (h : ι → List Bool → ℚ) (V : ℕ) + (hh : ∀ i v, |(h i v : ℝ)| ≤ (1 / 2 : ℝ)) : + Integrable (objective B π h V) μ := by + unfold objective + apply integrable_finsetSum + intro i _ + exact (integrable_truncated μ (π i) (h i) B.support V (hh i)).add + ((integrable_const (1 : ℝ)).indicator (LateDropBound.measurableSet_partialEvent B (π i) V)) + +/-- Separating the two parts of the finite objective recovers the actual +partial-rank probability sum. -/ +theorem integral_objective (μ : Measure Cantor) [IsFiniteMeasure μ] + (B : AffineBlock) (π : ι → ScanRule) (h : ι → List Bool → ℚ) (V : ℕ) + (hh : ∀ i v, |(h i v : ℝ)| ≤ (1 / 2 : ℝ)) : + (∫ X, objective B π h V X ∂μ) = + (∑ i, ∫ X, (StageFiniteWager.truncated (π i) (h i) B.support + ((π i).transcript X V) : ℝ) ∂μ) + StageRankLimit.partialMass μ B π V := by + unfold objective + rw [integral_finsetSum (f := fun i X => + (StageFiniteWager.truncated (π i) (h i) B.support ((π i).transcript X V) : ℝ) + + (LateDropBound.partialEvent B (π i) V).indicator (fun _ => (1 : ℝ)) X) + Finset.univ (fun i _ => + (integrable_truncated μ (π i) (h i) B.support V (hh i)).add + ((integrable_const (1 : ℝ)).indicator + (LateDropBound.measurableSet_partialEvent B (π i) V)))] + simp_rw [integral_add (integrable_truncated μ (π _) (h _) B.support V (hh _)) + ((integrable_const (1 : ℝ)).indicator (LateDropBound.measurableSet_partialEvent B (π _) V)), + integral_indicator_const _ (LateDropBound.measurableSet_partialEvent B (π _) V), + smul_eq_mul, mul_one] + exact Finset.sum_add_distrib + +/-- The old-stage objective is strictly below `4 * error` once the selected +support has total expected wager below `error` and the horizon's partial-rank +mass is below `3 * error`. -/ +theorem integral_objective_lt (μ : Measure Cantor) [IsFiniteMeasure μ] + (B : AffineBlock) (π : ι → ScanRule) (h : ι → List Bool → ℚ) (V : ℕ) + (hh : ∀ i v, |(h i v : ℝ)| ≤ (1 / 2 : ℝ)) (error : ℝ) + (hwager : (∑ i, ∫ X, StageWeights.supportWager (π i) + (fun v => (h i v : ℝ)) B.support X ∂μ) < error) + (hpartial : StageRankLimit.partialMass μ B π V < 3 * error) : + (∫ X, objective B π h V X ∂μ) < 4 * error := by + have hle : (∑ i, ∫ X, (StageFiniteWager.truncated (π i) (h i) B.support + ((π i).transcript X V) : ℝ) ∂μ) ≤ + ∑ i, ∫ X, StageWeights.supportWager (π i) (fun v => (h i v : ℝ)) B.support X ∂μ := by + apply Finset.sum_le_sum + intro i _ + exact integral_mono (integrable_truncated μ (π i) (h i) B.support V (hh i)) + (integrable_supportWager_of_half_bound μ (π i) (h i) B.support (hh i)) + (fun X => StageFiniteWager.truncated_transcript_le_supportWager (π i) (h i) B.support X V) + rw [integral_objective μ B π h V hh] + linarith + +/-- Every exact minimizer of the finite conditional objective has a cost +below the required budget. The selection of the minimizer can therefore be +performed by the finite rational search without extra advice. -/ +theorem minimizing_objective_lt {κ : Type*} [Finite κ] (old : κ → AffineBlock) + (B : AffineBlock) + (hold : Pairwise (fun i j => Disjoint (old i).support (old j).support)) + (hnew : ∀ k, Disjoint (old k).support B.support) + (π : ι → ScanRule) (h : ι → List Bool → ℚ) (V : ℕ) + (hh : ∀ i v, |(h i v : ℝ)| ≤ (1 / 2 : ℝ)) (error : ℝ) + (hwager : (∑ i, ∫ X, StageWeights.supportWager (π i) + (fun v => (h i v : ℝ)) B.support X ∂finiteStageLaw old) < error) + (hpartial : StageRankLimit.partialMass (finiteStageLaw old) B π V < 3 * error) + (y : Fin B.rank → ZMod 2) + (hmin : ∀ z, (∫ X, objective B π h V X ∂law old B y) ≤ + ∫ X, objective B π h V X ∂law old B z) : + (∫ X, objective B π h V X ∂law old B y) < 4 * error := by + let : IsProbabilityMeasure (finiteStageLaw old) := + finiteStageLaw_isProbabilityMeasure_of_disjoint old hold + obtain ⟨z, hz⟩ := exists_integral_cond_syndrome_le old B hold hnew + (integrable_objective (finiteStageLaw old) B π h V hh) + exact ((hmin z).trans hz).trans_lt + (integral_objective_lt (finiteStageLaw old) B π h V hh error hwager hpartial) + +end Klr.StageHorizonChoice diff --git a/LeanPool/KLRandomness/StageHorizonChoiceBounds.lean b/LeanPool/KLRandomness/StageHorizonChoiceBounds.lean new file mode 100644 index 0000000000..25012cc383 --- /dev/null +++ b/LeanPool/KLRandomness/StageHorizonChoiceBounds.lean @@ -0,0 +1,229 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.StageHorizonChoice + +/-! +# The early and tail estimates for the chosen syndrome + +An exact minimizer of the computable truncated-wager objective satisfies the +actual rank-drop early-wager estimate. The first-drop tail is preserved by +every syndrome, so the same selected syndrome satisfies both estimates. +These are one-stage statements for the actual conditional input laws. +-/ + +@[expose] public section + +noncomputable section + +namespace Klr.StageHorizonChoice + +open MeasureTheory ProbabilityTheory AffineBlock StageSyndrome +open scoped BigOperators ENNReal + +/-- The actual early rank-drop wager of a single block, expressed through +the existing family-based API. The unused family coordinates do not enter it. -/ +def earlyWager (B : AffineBlock) (π : ScanRule) (h : List Bool → ℚ) + (V : ℕ) : Cantor → ℝ := + EarlyLateWagers.earlyWager (fun _ => B) π (fun v => (h v : ℝ)) (fun _ => V) 0 + +/-- Reinsert the one-block quantity at any position of a stage sequence. -/ +theorem earlyWager_eq_family (B : ℕ → AffineBlock) (π : ScanRule) + (h : List Bool → ℚ) (V : ℕ → ℕ) (j : ℕ) : + earlyWager (B j) π h (V j) = + EarlyLateWagers.earlyWager B π (fun v => (h v : ℝ)) V j := rfl + +theorem earlyWager_nonneg (B : AffineBlock) (π : ScanRule) + (h : List Bool → ℚ) (V : ℕ) (X : Cantor) : 0 ≤ earlyWager B π h V X := + EarlyLateWagers.earlyWager_nonneg (fun _ => B) π _ (fun _ => V) 0 X + +theorem integrable_earlyWager (μ : Measure Cantor) [IsFiniteMeasure μ] + (B : AffineBlock) (π : ScanRule) (h : List Bool → ℚ) (V : ℕ) + (hh : ∀ v, |(h v : ℝ)| ≤ (1 / 2 : ℝ)) : + Integrable (earlyWager B π h V) μ := by + apply Integrable.of_bound + (EarlyLateWagers.measurable_earlyWager (fun _ => B) π _ (fun _ => V) 0).aestronglyMeasurable + ((V : ℝ) / 2) + apply Filter.Eventually.of_forall + intro X + rw [Real.norm_eq_abs] + change |earlyWager B π h V X| ≤ _ + rw [abs_of_nonneg (earlyWager_nonneg B π h V X)] + exact EarlyLateWagers.earlyWager_le_half_horizon (fun _ => B) π _ (fun _ => V) hh 0 X + +variable {ι : Type*} [Fintype ι] + +/-- The computable truncated objective dominates the sum of actual early +rank-drop wagers plus the partial-rank probabilities. -/ +theorem sum_early_partial_le_objective (μ : Measure Cantor) [IsFiniteMeasure μ] + (B : AffineBlock) (π : ι → ScanRule) (h : ι → List Bool → ℚ) (V : ℕ) + (hh : ∀ i v, |(h i v : ℝ)| ≤ (1 / 2 : ℝ)) : + (∑ i, ((∫ X, earlyWager B (π i) (h i) V X ∂μ) + + μ.real (LateDropBound.partialEvent B (π i) V))) ≤ + ∫ X, objective B π h V X ∂μ := by + rw [integral_objective μ B π h V hh, StageRankLimit.partialMass, + ← Finset.sum_add_distrib] + apply Finset.sum_le_sum + intro i _ + apply add_le_add _ le_rfl + exact integral_mono (integrable_earlyWager μ B (π i) (h i) V (hh i)) + (integrable_truncated μ (π i) (h i) B.support V (hh i)) + (fun X => StageFiniteWager.earlyWager_le_truncated (fun _ => B) (π i) (h i) + (fun _ => V) 0 X) + +/-- Every exact minimizing syndrome satisfies the simultaneous real-valued +version of estimate (6). Its objective may count additional support queries. -/ +theorem minimizing_syndrome_early_sum_lt {κ : Type*} [Finite κ] + (old : κ → AffineBlock) (B : AffineBlock) + (hold : Pairwise (fun i j => Disjoint (old i).support (old j).support)) + (hnew : ∀ k, Disjoint (old k).support B.support) + (π : ι → ScanRule) (h : ι → List Bool → ℚ) (V : ℕ) + (hh : ∀ i v, |(h i v : ℝ)| ≤ (1 / 2 : ℝ)) (error : ℝ) + (hwager : (∑ i, ∫ X, StageWeights.supportWager (π i) + (fun v => (h i v : ℝ)) B.support X ∂finiteStageLaw old) < error) + (hpartial : StageRankLimit.partialMass (finiteStageLaw old) B π V < 3 * error) + (y : Fin B.rank → ZMod 2) + (hmin : ∀ z, (∫ X, objective B π h V X ∂law old B y) ≤ + ∫ X, objective B π h V X ∂law old B z) : + (∑ i, ((∫ X, earlyWager (withSyndrome B y) (π i) (h i) V X ∂law old B y) + + (law old B y).real (LateDropBound.partialEvent (withSyndrome B y) (π i) V))) < + 4 * error := + (sum_early_partial_le_objective (law old B y) (withSyndrome B y) π h V hh).trans_lt + (minimizing_objective_lt old B hold hnew π h V hh error hwager hpartial y hmin) + +/-- Existence of an admissible syndrome follows from actual uniform +syndrome averaging. This theorem does not assume a minimizing oracle. -/ +theorem exists_syndrome_early_sum_lt {κ : Type*} [Finite κ] + (old : κ → AffineBlock) (B : AffineBlock) + (hold : Pairwise (fun i j => Disjoint (old i).support (old j).support)) + (hnew : ∀ k, Disjoint (old k).support B.support) + (π : ι → ScanRule) (h : ι → List Bool → ℚ) (V : ℕ) + (hh : ∀ i v, |(h i v : ℝ)| ≤ (1 / 2 : ℝ)) (error : ℝ) + (hwager : (∑ i, ∫ X, StageWeights.supportWager (π i) + (fun v => (h i v : ℝ)) B.support X ∂finiteStageLaw old) < error) + (hpartial : StageRankLimit.partialMass (finiteStageLaw old) B π V < 3 * error) : + ∃ y : Fin B.rank → ZMod 2, + (∑ i, ((∫ X, earlyWager (withSyndrome B y) (π i) (h i) V X ∂law old B y) + + (law old B y).real (LateDropBound.partialEvent (withSyndrome B y) (π i) V))) < + 4 * error := by + let : IsProbabilityMeasure (finiteStageLaw old) := + finiteStageLaw_isProbabilityMeasure_of_disjoint old hold + obtain ⟨y, hy⟩ := exists_integral_cond_syndrome_le old B hold hnew + (integrable_objective (finiteStageLaw old) B π h V hh) + refine ⟨y, ?_⟩ + exact ((sum_early_partial_le_objective (law old B y) + (withSyndrome B y) π h V hh).trans hy).trans_lt + (integral_objective_lt (finiteStageLaw old) B π h V hh error hwager hpartial) + +/-- Conditioning on any syndrome preserves the probability of a first drop +after the horizon, by the full-rank pre-drop cylinder identity. -/ +theorem law_rankDropTailEvent {κ : Type*} [Finite κ] (old : κ → AffineBlock) + (B : AffineBlock) + (hold : Pairwise (fun i j => Disjoint (old i).support (old j).support)) + (hnew : ∀ k, Disjoint (old k).support B.support) + (y : Fin B.rank → ZMod 2) (π : ScanRule) (V : ℕ) : + law old B y (StoppingTranscript.rankDropTailEvent (withSyndrome B y) π V) = + finiteStageLaw old (StoppingTranscript.rankDropTailEvent B π V) := by + rw [law, finiteStageLaw, + cond_cond_eq_cond_inter (measurableSet_familyEvent old) (withSyndrome B y).measurableSet_event] + simpa only [rankDropTailEvent_withSyndrome, finiteStageLaw] using + StoppingTranscript.nextStage_rankDropTail old (withSyndrome B y) hold hnew π V + +theorem law_real_rankDropTailEvent {κ : Type*} [Finite κ] (old : κ → AffineBlock) + (B : AffineBlock) + (hold : Pairwise (fun i j => Disjoint (old i).support (old j).support)) + (hnew : ∀ k, Disjoint (old k).support B.support) + (y : Fin B.rank → ZMod 2) (π : ScanRule) (V : ℕ) : + (law old B y).real (StoppingTranscript.rankDropTailEvent (withSyndrome B y) π V) = + (finiteStageLaw old).real (StoppingTranscript.rankDropTailEvent B π V) := + congrArg ENNReal.toReal (law_rankDropTailEvent old B hold hnew y π V) + +/-- The summed tail bound produced by the horizon search survives every +syndrome choice, in particular the computable objective minimizer. -/ +theorem syndrome_sum_tail_lt {κ : Type*} [Finite κ] (old : κ → AffineBlock) + (B : AffineBlock) + (hold : Pairwise (fun i j => Disjoint (old i).support (old j).support)) + (hnew : ∀ k, Disjoint (old k).support B.support) + (π : ι → ScanRule) (V : ℕ) (error : ℝ) + (htail : (∑ i, (finiteStageLaw old).real + (StoppingTranscript.rankDropTailEvent B (π i) V)) < 2 * error) + (y : Fin B.rank → ZMod 2) : + (∑ i, (law old B y).real + (StoppingTranscript.rankDropTailEvent (withSyndrome B y) (π i) V)) < 2 * error := by + simpa only [law_real_rankDropTailEvent old B hold hnew] using htail + +/-- Convert the real-valued early estimate to the nonnegative lower-integral +form used by `StageEstimates`. -/ +theorem early_lintegral_add_measure_le (μ : Measure Cantor) [IsFiniteMeasure μ] + (B : AffineBlock) (π : ScanRule) (h : List Bool → ℚ) (V : ℕ) + (hh : ∀ v, |(h v : ℝ)| ≤ (1 / 2 : ℝ)) {c : ℝ} + (hbound : (∫ X, earlyWager B π h V X ∂μ) + + μ.real (LateDropBound.partialEvent B π V) ≤ c) : + (∫⁻ X, ENNReal.ofReal (earlyWager B π h V X) ∂μ) + + μ (LateDropBound.partialEvent B π V) ≤ ENNReal.ofReal c := by + have hn : 0 ≤ ∫ X, earlyWager B π h V X ∂μ := + integral_nonneg (earlyWager_nonneg B π h V) + rw [← ofReal_integral_eq_lintegral_ofReal (integrable_earlyWager μ B π h V hh) + (Filter.Eventually.of_forall (earlyWager_nonneg B π h V))] + calc + _ = ENNReal.ofReal ((∫ X, earlyWager B π h V X ∂μ) + + μ.real (LateDropBound.partialEvent B π V)) := by + rw [ENNReal.ofReal_add hn measureReal_nonneg, + Measure.real, ENNReal.ofReal_toReal (measure_ne_top μ _)] + _ ≤ _ := ENNReal.ofReal_le_ofReal hbound + +/-- One chosen minimizing syndrome simultaneously satisfies (6) and (7) +for every protected strategy, in the measure types used by the stage API. -/ +theorem minimizing_syndrome_stage_bounds {κ : Type*} [Finite κ] + (old : κ → AffineBlock) (B : AffineBlock) + (hold : Pairwise (fun i j => Disjoint (old i).support (old j).support)) + (hnew : ∀ k, Disjoint (old k).support B.support) + (π : ι → ScanRule) (h : ι → List Bool → ℚ) (V : ℕ) + (hh : ∀ i v, |(h i v : ℝ)| ≤ (1 / 2 : ℝ)) (error : ℝ) + (hwager : (∑ i, ∫ X, StageWeights.supportWager (π i) + (fun v => (h i v : ℝ)) B.support X ∂finiteStageLaw old) < error) + (hpartial : StageRankLimit.partialMass (finiteStageLaw old) B π V < 3 * error) + (htail : (∑ i, (finiteStageLaw old).real + (StoppingTranscript.rankDropTailEvent B (π i) V)) < 2 * error) + (y : Fin B.rank → ZMod 2) + (hmin : ∀ z, (∫ X, objective B π h V X ∂law old B y) ≤ + ∫ X, objective B π h V X ∂law old B z) : + ∀ i, + ((∫⁻ X, ENNReal.ofReal (earlyWager (withSyndrome B y) (π i) (h i) V X) + ∂law old B y) + + law old B y (LateDropBound.partialEvent (withSyndrome B y) (π i) V) ≤ + ENNReal.ofReal (4 * error)) ∧ + law old B y (StoppingTranscript.rankDropTailEvent (withSyndrome B y) (π i) V) ≤ + ENNReal.ofReal (2 * error) := by + have hearly := minimizing_syndrome_early_sum_lt old B hold hnew π h V hh error + hwager hpartial y hmin + have htail' := syndrome_sum_tail_lt old B hold hnew π V error htail y + intro i + constructor + · apply early_lintegral_add_measure_le (law old B y) (withSyndrome B y) (π i) (h i) V (hh i) + apply le_trans _ hearly.le + refine Finset.single_le_sum (f := fun j : ι => + (∫ X, earlyWager (withSyndrome B y) (π j) (h j) V X ∂law old B y) + + (law old B y).real (LateDropBound.partialEvent (withSyndrome B y) (π j) V)) + (s := Finset.univ) (a := i) ?_ (Finset.mem_univ i) + intro j _ + exact add_nonneg + (integral_nonneg (earlyWager_nonneg (withSyndrome B y) (π j) (h j) V)) + measureReal_nonneg + · have hi : (law old B y).real + (StoppingTranscript.rankDropTailEvent (withSyndrome B y) (π i) V) ≤ 2 * error := by + apply le_trans _ htail'.le + exact Finset.single_le_sum (f := fun j : ι => (law old B y).real + (StoppingTranscript.rankDropTailEvent (withSyndrome B y) (π j) V)) + (s := Finset.univ) (fun _ _ => measureReal_nonneg) (Finset.mem_univ i) + have hle := ENNReal.ofReal_le_ofReal hi + simpa only [Measure.real, ENNReal.ofReal_toReal (measure_ne_top (law old B y) _)] using hle + +end Klr.StageHorizonChoice diff --git a/LeanPool/KLRandomness/StageHorizonComputable.lean b/LeanPool/KLRandomness/StageHorizonComputable.lean new file mode 100644 index 0000000000..17a80ba95f --- /dev/null +++ b/LeanPool/KLRandomness/StageHorizonComputable.lean @@ -0,0 +1,167 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.StageHorizon +public import LeanPool.KLRandomness.PoolAdviceComputable +public import Mathlib.Computability.PartrecCode + +/-! +# The uniform horizon-search program + +For any uniformly computable rational functions `u` and `v`, one fixed +partial-recursive program searches for the first horizon passing the two +stage inequalities. Its input is the finite construction parameter together +with the bounded integer advice. Neither limiting probability nor a modulus +of convergence is supplied to the program. + +The finite parameter type may contain the trial rank and the selected sparse +candidate index. All constants and the programs computing `u` and `v` remain +fixed outside the input quantifier. +-/ + +@[expose] public section + +namespace Klr.StageHorizon + +open Filter RationalComputability +open scoped Topology + +variable {α : Type*} + +/-- The exact Boolean verifier. The second component of the input is the +integer advice; the search horizon is a separate argument. -/ +def check (error : ℚ) (u v : α → ℕ → ℚ) (input : α × ℕ) (horizon : ℕ) : Bool := + decide (u input.1 horizon < 3 * error) && + decide (((input.2 : ℚ) - 1) * error < v input.1 horizon) + +theorem check_eq_true (error : ℚ) (u v : α → ℕ → ℚ) + (input : α × ℕ) (horizon : ℕ) : + check error u v input horizon = true ↔ + Accepted error (u input.1) (v input.1) input.2 horizon := by + simp only [check, Bool.and_eq_true, decide_eq_true_eq, Accepted] + +/-- The verifier is uniformly computable in the construction parameter, +integer advice, and proposed horizon. -/ +theorem computable_check [Primcodable α] (error : ℚ) {u v : α → ℕ → ℚ} + (hu : Computable₂ u) (hv : Computable₂ v) : + Computable₂ (check error u v) := by + have ha : Computable (fun p : (α × ℕ) × ℕ => p.1.1) := + Computable.fst.comp Computable.fst + have hb : Computable (fun p : (α × ℕ) × ℕ => (p.1.2 : ℚ)) := + primrec_rat_natCast.to_comp.comp (Computable.snd.comp Computable.fst) + have hthreshold := primrec_rat_mul.to_comp.comp + (primrec_rat_sub.to_comp.comp hb (Computable.const 1)) (Computable.const error) + exact Primrec.and.to_comp.comp + (PoolAdvice.computable_rat_lt.comp (hu.comp ha Computable.snd) + (Computable.const (3 * error))) + (PoolAdvice.computable_rat_lt.comp hthreshold (hv.comp ha Computable.snd)) + +/-- Search successively through the natural-number horizons and return the +first one passing the rational tests. -/ +def search (error : ℚ) (u v : α → ℕ → ℚ) (input : α × ℕ) : Part ℕ := + Nat.rfind fun horizon => Part.some (check error u v input horizon) + +theorem partrec_search [Primcodable α] (error : ℚ) {u v : α → ℕ → ℚ} + (hu : Computable₂ u) (hv : Computable₂ v) : + Partrec (search error u v) := + Partrec.rfind (computable_check error hu hv).partrec.to₂ + +/-- A returned horizon satisfies the two finite tests. -/ +theorem search_spec {error : ℚ} {u v : α → ℕ → ℚ} {input : α × ℕ} + {horizon : ℕ} (h : horizon ∈ search error u v input) : + Accepted error (u input.1) (v input.1) input.2 horizon := by + apply (check_eq_true error u v input horizon).mp + exact (Part.mem_some_iff.mp (Nat.rfind_spec h)).symm + +/-- The search returns the first accepted horizon, not an arbitrary witness. -/ +theorem search_min {error : ℚ} {u v : α → ℕ → ℚ} {input : α × ℕ} + {horizon : ℕ} (h : horizon ∈ search error u v input) : + ∀ n < horizon, ¬ Accepted error (u input.1) (v input.1) input.2 n := by + intro n hn hnaccept + have hnfalse := Nat.rfind_min h hn + have hntrue := (check_eq_true error u v input n).mpr hnaccept + simp only [hntrue, Part.mem_some_iff, Bool.false_eq_true] at hnfalse + +/-- Halting requires precisely a finite accepted horizon. The limiting +analytic argument is used to establish this existence separately. -/ +theorem search_dom_iff (error : ℚ) (u v : α → ℕ → ℚ) (input : α × ℕ) : + (search error u v input).Dom ↔ + ∃ horizon, Accepted error (u input.1) (v input.1) input.2 horizon := by + constructor + · intro hdom + obtain ⟨horizon, hhorizon⟩ := Part.dom_iff_mem.mp hdom + exact ⟨horizon, search_spec hhorizon⟩ + · rintro ⟨horizon, hhorizon⟩ + apply Nat.rfind_dom.mpr + refine ⟨horizon, ?_, fun {_} _ => trivial⟩ + exact Part.mem_some_iff.mpr ((check_eq_true error u v input horizon).mpr hhorizon).symm + +/-- Use the canonical primitive encoding for the complete program input. -/ +def encodeInput [Primcodable α] (input : α × ℕ) : ℕ := + @Encodable.encode (α × ℕ) (inferInstance : Primcodable (α × ℕ)).toEncodable input + +/-- There is one fixed program for every parameter and every advice value. +The output is the horizon itself, so it need not be included in the input. -/ +theorem exists_search_program [Primcodable α] (error : ℚ) {u v : α → ℕ → ℚ} + (hu : Computable₂ u) (hv : Computable₂ v) : + ∃ code : Nat.Partrec.Code, ∀ input : α × ℕ, + code.eval (encodeInput input) = search error u v input := by + obtain ⟨code, hcode⟩ := Nat.Partrec.Code.exists_code.mp (partrec_search error hu hv) + refine ⟨code, fun input => ?_⟩ + rw [hcode] + simp only [encodeInput, Encodable.encodek, Part.coe_some, Part.bind_some] + exact Part.map_id' (fun _ => rfl) _ + +/-- The bounded advice provided by the analytic limit argument makes the +actual search halt, and its output satisfies both the early-rank and tail +bounds. No limit is evaluated by the search. -/ +theorem exists_bounded_advice_search {error : ℚ} (herror : 0 < error) + {u v : α → ℕ → ℚ} (input : α) {uLimit vLimit : ℝ} {protectedCount : ℕ} + (hu : Tendsto (fun n => (u input n : ℝ)) atTop (𝓝 uLimit)) + (hv : Tendsto (fun n => (v input n : ℝ)) atTop (𝓝 vLimit)) + (huLimit : uLimit ≤ 2 * (error : ℝ)) (hvLimit : 0 ≤ vLimit) + (hbound : vLimit ≤ protectedCount) : + ∃ advice, advice ≤ adviceBound error protectedCount ∧ + (search error u v (input, advice)).Dom ∧ + ∀ horizon, horizon ∈ search error u v (input, advice) → + Accepted error (u input) (v input) advice horizon ∧ + vLimit - (v input horizon : ℝ) < 2 * (error : ℝ) := by + obtain ⟨advice, hadvice, _, heventually, htail⟩ := + exists_bounded_advice herror hu hv huLimit hvLimit hbound + refine ⟨advice, hadvice, (search_dom_iff error u v (input, advice)).mpr + heventually.exists, ?_⟩ + intro horizon hhorizon + exact ⟨search_spec hhorizon, htail horizon (search_spec hhorizon)⟩ + +/-- The fixed program realizes the analytic construction for every parameter +whose two rational sequences have the requisite limits. The program is +chosen before the parameter, the limits, and the bounded advice. -/ +theorem exists_uniform_bounded_horizon_program [Primcodable α] + {error : ℚ} (herror : 0 < error) + {u v : α → ℕ → ℚ} (hu : Computable₂ u) (hv : Computable₂ v) : + ∃ code : Nat.Partrec.Code, + (∀ input : α × ℕ, code.eval (encodeInput input) = search error u v input) ∧ + ∀ (input : α) (uLimit vLimit : ℝ) (protectedCount : ℕ), + Tendsto (fun n => (u input n : ℝ)) atTop (𝓝 uLimit) → + Tendsto (fun n => (v input n : ℝ)) atTop (𝓝 vLimit) → + uLimit ≤ 2 * (error : ℝ) → 0 ≤ vLimit → vLimit ≤ protectedCount → + ∃ advice, advice ≤ adviceBound error protectedCount ∧ + ∃ horizon, horizon ∈ code.eval (encodeInput (input, advice)) ∧ + Accepted error (u input) (v input) advice horizon ∧ + vLimit - (v input horizon : ℝ) < 2 * (error : ℝ) := by + obtain ⟨code, hcode⟩ := exists_search_program error hu hv + refine ⟨code, hcode, ?_⟩ + intro input uLimit vLimit protectedCount huconv hvconv huLimit hvLimit hbound + obtain ⟨advice, hadvice, hdom, hspec⟩ := + exists_bounded_advice_search herror input huconv hvconv huLimit hvLimit hbound + obtain ⟨horizon, hhorizon⟩ := Part.dom_iff_mem.mp hdom + exact ⟨advice, hadvice, horizon, by rwa [hcode], hspec horizon hhorizon⟩ + +end Klr.StageHorizon diff --git a/LeanPool/KLRandomness/StageOneStep.lean b/LeanPool/KLRandomness/StageOneStep.lean new file mode 100644 index 0000000000..19957ec9db --- /dev/null +++ b/LeanPool/KLRandomness/StageOneStep.lean @@ -0,0 +1,160 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.StageOneStepHorizon +public import LeanPool.KLRandomness.StagePreparedIndex +public import LeanPool.KLRandomness.StageCandidateBridge +public import LeanPool.KLRandomness.StageStep + +/-! +# A complete stage extension from the prepared finite data + +The preparation has already selected one sufficiently large rank and one +good candidate while keeping the reconstruction program fixed. Here bounded +integer advice makes its actual horizon search halt. The same program then +computes the syndrome and a certified affine code. All four stage estimates +and the short-description budget are attached to that actual output. +-/ + +@[expose] public section + +noncomputable section + +namespace Klr.StageOneStep + +open MeasureTheory ProbabilityTheory SparseListSearch StageCandidate StagePrepared +open scoped BigOperators ENNReal + +/-- Prepared finite data produce a fully coded stage result. The only +cutoff hypothesis separates the old supports from the prepared pool. -/ +theorem result_of_prepared + (s : ℕ → BettingStrategy) (H : ℕ → Set Cantor) (old : ℕ → AffineBlock) + (hold : Pairwise (fun i j => Disjoint (old i).support (old j).support)) + (n z : ℕ) {error : ℚ} (herror : 0 < error) + (P : Prepared s H old n z error) + (hz : ∀ k < n, ∀ p ∈ (old k).support, p < z) : + Nonempty (Result old n (protectedRules s n) (fun i => H i) + error P.rank n P.pool) := by + let rules := protectedRules s n + let cs := StagePrefixCode.prefixHeader old n + let a := P.candidates.get P.index + have ha : GoodEntry P.pool.length (SparseParameters.supportSize P.rank) P.rank a := + StageCandidateBridge.candidate_goodEntry P.goodPool.1 P.list_eval P.index + let C₀ := block P.pool.get P.goodPool.2.1.injective_get a ha 0 + have heq : StagePreHorizon.candidate P.goodPool.1 P.goodPool.2.1 + P.list_eval P.index 0 = C₀ := + StageCandidateBridge.candidate_eq_block P.goodPool.1 P.goodPool.2.1 + P.list_eval P.index ha 0 + have hnew : ∀ k < n, Disjoint (old k).support C₀.support := by + intro k hk + apply Finset.disjoint_left.mpr + intro p hpold hpnew + have hpG := block_support_subset P.pool P.goodPool.2.1 a ha 0 hpnew + exact (not_lt_of_ge (P.goodPool.2.2.1 p (List.mem_toFinset.mp hpG))) (hz k hk p hpold) + have hwager : (∑ i : Fin rules.length, StageChoice.wagerCost (PrefixStage.law old n) + (rules.get i) C₀) < (error : ℝ) := by + have h := (P.scores 0).1 + rw [heq] at h + have h' := (sum_protectedRules s n (fun i => + StageChoice.wagerCost (PrefixStage.law old n) (s i) C₀)).trans_lt h + simpa only [rules, get_protectedRules] using h' + have hhigh : (∑ i : Fin rules.length, (PrefixStage.law old n).real + (StagePreHorizon.highMissInput (rules.get i) (H i) P.pool)) < (error : ℝ) := by + have h' := (sum_protectedRules s n (fun i => + (PrefixStage.law old n).real (StagePreHorizon.highMissInput (s i) (H i) P.pool))).trans_lt + (P.high_miss n le_rfl) + simpa only [rules, get_protectedRules] using h' + have hlow : ∀ k ≤ n, (∑ i : Fin rules.length, (PrefixStage.law old k).real + (StagePreHorizon.lowDropInput (rules.get i) (H i) C₀)) < (error : ℝ) := by + intro k hk + have h := (P.scores 0).2 k hk + rw [heq] at h + have h' := (sum_protectedRules s n (fun i => + (PrefixStage.law old k).real (StagePreHorizon.lowDropInput (s i) (H i) C₀))).trans_lt h + simpa only [rules, get_protectedRules] using h' + obtain ⟨b, hb, V, hV, hpartial, htail⟩ := exists_computed_horizon old hold n rules + (fun i => H i) cs (StagePrefixCode.law_prefixHeader old n) P.pool P.goodPool.2.1 + a ha herror hhigh (hlow n le_rfl) + have hbounds := bounds_of_computed_horizon old hold n rules (fun i => H i) cs + (StagePrefixCode.law_prefixHeader old n) P.pool P.goodPool.2.1 P.rank_pos a ha + hnew hwager hhigh hlow V hpartial htail + obtain ⟨c, hc, hvalid, hrank, hevent⟩ := StageSyndromeObjective.finish_halts + rules cs P.pool P.goodPool.2.1 a ha V + have hget : P.candidates.getD P.index.val default = a := + List.getD_eq_get P.candidates default P.index + have hrun := StageReconstruction.mem_run_of_witnesses rules cs P.poolProgram + error P.density P.listError + (r := P.rank) (q := P.index.val) (b := b) (G := P.pool) (L := P.candidates) + (V := V) (c := c) + (by simpa only [SparseParameters.blockSize] using P.pool_eval) P.list_eval + (by simpa only [hget] using hV) (by simpa only [hget] using hc) + have hruns : c ∈ AffineDescription.run + (AffineDescription.programFor P.program (Nat.pair P.rank (Nat.pair P.index.val b))) := by + rw [P.program_correct] + exact hrun + refine ⟨{ + block := chosenBlock rules cs P.pool P.goodPool.2.1 a ha V + horizon := V + code := c + program := AffineDescription.programFor P.program (Nat.pair P.rank (Nat.pair P.index.val b)) + valid := hvalid + runs := hruns + code_rank := hrank + block_rank := rfl + event_eq := hevent + budget := P.program_budget b ?_ + support_subset := block_support_subset P.pool P.goodPool.2.1 a ha _ + bounds := hbounds }⟩ + simpa only [rules, length_protectedRules] using hb + +/-- The finite-list result supplies the natural-number indexed recurrence +relation used by the global stage construction. -/ +theorem Result.to_step {s : ℕ → BettingStrategy} {H : ℕ → Set Cantor} + {old : ℕ → AffineBlock} {n z : ℕ} {error : ℚ} {r : ℕ} {G : List ℕ} + (R : Result old n (protectedRules s n) (fun i => H i) error r n G) + (hG : ∀ p ∈ G, z ≤ p) : + StageRecursion.Step s H old n z error R.block R.horizon := by + refine ⟨?_, ?_, ?_, ?_, ?_, ?_⟩ + · intro p hp + exact hG p (List.mem_toFinset.mp (R.support_subset hp)) + · intro i hi + let j : Fin (protectedRules s n).length := ⟨i, by rw [length_protectedRules]; omega⟩ + simpa only [get_protectedRules, j] using R.bounds.early j + · intro i hi + let j : Fin (protectedRules s n).length := ⟨i, by rw [length_protectedRules]; omega⟩ + simpa only [get_protectedRules, j] using R.bounds.tail j + · intro i hi + let j : Fin (protectedRules s n).length := ⟨i, by rw [length_protectedRules]; omega⟩ + simpa only [get_protectedRules, j] using R.bounds.high j + · intro a ha i hi + let j : Fin (protectedRules s n).length := ⟨i, by rw [length_protectedRules]; omega⟩ + simpa only [get_protectedRules, lowDropInput_eq, j] using R.bounds.low a ha j + · refine ⟨R.program, R.code, R.runs, R.valid, ?_, ?_, R.event_eq⟩ + · exact R.code_rank.trans R.block_rank.symm + · simpa only [R.code_rank] using R.budget + +end Klr.StageOneStep + +namespace Klr.StagePrepared.Prepared + +/-- One prepared stage really extends the construction. This theorem has +no supplied syndrome, horizon, execution witness, or shortness assumption: +all of them are obtained from the prepared data and the analytic estimates. -/ +theorem to_step {s : ℕ → BettingStrategy} {H : ℕ → Set Cantor} + {old : ℕ → AffineBlock} + (hold : Pairwise (fun i j => Disjoint (old i).support (old j).support)) + {n z : ℕ} {error : ℚ} (herror : 0 < error) + (P : StagePrepared.Prepared s H old n z error) + (hz : ∀ k < n, ∀ p ∈ (old k).support, p < z) : + ∃ C V, StageRecursion.Step s H old n z error C V := by + obtain ⟨R⟩ := StageOneStep.result_of_prepared s H old hold n z herror P hz + exact ⟨R.block, R.horizon, R.to_step P.goodPool.2.2.1⟩ + +end Klr.StagePrepared.Prepared diff --git a/LeanPool/KLRandomness/StageOneStepBounds.lean b/LeanPool/KLRandomness/StageOneStepBounds.lean new file mode 100644 index 0000000000..002f6c2067 --- /dev/null +++ b/LeanPool/KLRandomness/StageOneStepBounds.lean @@ -0,0 +1,115 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.StageOneStepDefs + +/-! +# All four estimates for the computed one-stage block + +The syndrome is the output of the actual finite minimization program. The +early and tail estimates follow from that minimum and the reconstructed +horizon; the high and low estimates survive changing the syndrome because +the unread ranks depend only on the matrix and queried positions. +-/ + +@[expose] public section + +noncomputable section + +namespace Klr.StageOneStep + +open MeasureTheory ProbabilityTheory SparseListSearch StageCandidate +open scoped BigOperators ENNReal + +theorem measure_le_of_real_le (μ : Measure Cantor) [IsFiniteMeasure μ] + (E : Set Cantor) {c : ℝ} (h : μ.real E ≤ c) : μ E ≤ ENNReal.ofReal c := by + have he := ENNReal.ofReal_le_ofReal h + simpa only [Measure.real, ENNReal.ofReal_toReal (measure_ne_top μ E)] using he + +/-- A concrete computed syndrome satisfies all four stage bounds, once the +selected candidate and the actual finite horizon have the proved score +bounds. No syndrome is supplied as non-effective advice. -/ +theorem bounds_of_computed_horizon + (old : ℕ → AffineBlock) + (hold : Pairwise (fun i j => Disjoint (old i).support (old j).support)) + (n : ℕ) (rules : List BettingStrategy) (H : Fin rules.length → Set Cantor) + (cs : List AffineCode.Data) + (hcs : StageFiniteProbability.law cs = PrefixStage.law old n) + (G : List ℕ) (hG : G.Nodup) {m r : ℕ} (hr : 0 < r) + (a : Entry) (ha : GoodEntry G.length m r a) + (hnew : ∀ k < n, Disjoint (old k).support + (block G.get hG.injective_get a ha 0).support) + {error : ℚ} + (hwager : (∑ i : Fin rules.length, StageChoice.wagerCost (PrefixStage.law old n) + (rules.get i) (block G.get hG.injective_get a ha 0)) < (error : ℝ)) + (hhigh : (∑ i : Fin rules.length, (PrefixStage.law old n).real + (StagePreHorizon.highMissInput (rules.get i) (H i) G)) < (error : ℝ)) + (hlow : ∀ k ≤ n, (∑ i : Fin rules.length, (PrefixStage.law old k).real + (StagePreHorizon.lowDropInput (rules.get i) (H i) + (block G.get hG.injective_get a ha 0))) < (error : ℝ)) + (V : ℕ) + (hpartial : StageRankLimit.partialMass (PrefixStage.law old n) + (block G.get hG.injective_get a ha 0) + (fun i : Fin rules.length => (rules.get i).normalize.scan) V < 3 * (error : ℝ)) + (htail : (∑ i : Fin rules.length, (PrefixStage.law old n).real + (StoppingTranscript.rankDropTailEvent (block G.get hG.injective_get a ha 0) + (rules.get i).normalize.scan V)) < 2 * (error : ℝ)) : + Bounds old n rules H error (chosenBlock rules cs G hG a ha V) V := by + let C₀ := block G.get hG.injective_get a ha 0 + let y := SparseSearch.wordVector r (StageSyndromeObjective.chosen rules cs G a V) + let π (i : Fin rules.length) := (rules.get i).normalize.scan + let h (i : Fin rules.length) := StageFiniteWager.normalizedWager (rules.get i) + have hmin : ∀ z : Fin C₀.rank → ZMod 2, + (∫ X, StageHorizonChoice.objective C₀ π h V X + ∂StageHorizonChoice.law (PrefixStage.prefixFamily old n) C₀ y) ≤ + ∫ X, StageHorizonChoice.objective C₀ π h V X + ∂StageHorizonChoice.law (PrefixStage.prefixFamily old n) C₀ z := by + intro z + change Fin r → ZMod 2 at z + simpa only [C₀, π, h, y, StageHorizonChoice.law, hcs, PrefixStage.law, + withSyndrome_block G hG a ha 0] using + StageSyndromeObjective.chosen_minimizes_integral rules cs G hG a ha V z + have hw : (∑ i, ∫ X, StageWeights.supportWager (π i) + (fun v => (h i v : ℝ)) C₀.support X ∂AffineBlock.finiteStageLaw + (PrefixStage.prefixFamily old n)) < (error : ℝ) := by + simpa only [C₀, h, π, StageFiniteWager.cast_normalizedWager, + StageChoice.wagerCost, PrefixStage.law] using hwager + have hpoint := StageHorizonChoice.minimizing_syndrome_stage_bounds + (PrefixStage.prefixFamily old n) C₀ (PrefixStage.prefixFamily_pairwise old hold n) + (fun k => hnew k.val k.isLt) π h V + (fun i => StageFiniteWager.normalizedWager_abs_le_half (rules.get i)) + (error : ℝ) hw hpartial htail y hmin + let : IsProbabilityMeasure (PrefixStage.law old n) := + PrefixStage.law_isProbabilityMeasure old hold n + refine ⟨?_, ?_, ?_, ?_⟩ + · intro i + simpa only [StageHorizonChoice.earlyWager, StageHorizonChoice.law, C₀, y, + h, π, StageFiniteWager.cast_normalizedWager, PrefixStage.law, chosenBlock, + withSyndrome_block G hG a ha 0] using (hpoint i).1 + · intro i + exact (hpoint i).2 + · intro i + apply measure_le_of_real_le + apply le_trans (measureReal_mono (high_noDrop_subset_highMiss (rules.get i) (H i) + (chosenBlock rules cs G hG a ha V) G (block_support_subset G hG a ha y) hr)) + apply le_trans _ hhigh.le + exact Finset.single_le_sum (f := fun j : Fin rules.length => + (PrefixStage.law old n).real (StagePreHorizon.highMissInput (rules.get j) (H j) G)) + (s := Finset.univ) (fun _ _ => measureReal_nonneg) (Finset.mem_univ i) + · intro k hk i + let : IsProbabilityMeasure (PrefixStage.law old k) := + PrefixStage.law_isProbabilityMeasure old hold k + apply measure_le_of_real_le + apply le_trans _ (hlow k hk).le + exact Finset.single_le_sum (f := fun j : Fin rules.length => + (PrefixStage.law old k).real (StagePreHorizon.lowDropInput (rules.get j) (H j) C₀)) + (s := Finset.univ) (fun _ _ => measureReal_nonneg) (Finset.mem_univ i) + +end Klr.StageOneStep diff --git a/LeanPool/KLRandomness/StageOneStepDefs.lean b/LeanPool/KLRandomness/StageOneStepDefs.lean new file mode 100644 index 0000000000..c88c88ca90 --- /dev/null +++ b/LeanPool/KLRandomness/StageOneStepDefs.lean @@ -0,0 +1,137 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.StageHorizonChoiceBounds +public import LeanPool.KLRandomness.StagePreHorizon +public import LeanPool.KLRandomness.StagePrefixCode +public import LeanPool.KLRandomness.StageSyndromeObjective +public import LeanPool.KLRandomness.AffineDescription + +/-! +# The result of one actual stage extension + +The stage result contains an affine block, its reconstructed horizon, a +valid finite code and an actual short program producing that code. Its four +probability estimates refer to the actual previous and new conditional laws. +-/ + +@[expose] public section + +noncomputable section + +namespace Klr.StageOneStep + +open MeasureTheory ProbabilityTheory +open scoped BigOperators ENNReal + +/-- The four estimates required of a new block after a fixed old prefix. -/ +structure Bounds (old : ℕ → AffineBlock) (n : ℕ) (rules : List BettingStrategy) + (H : Fin rules.length → Set Cantor) (error : ℚ) (C : AffineBlock) (V : ℕ) : Prop where + early : ∀ i : Fin rules.length, + (∫⁻ X, ENNReal.ofReal (EarlyLateWagers.earlyWager (fun _ => C) + (rules.get i).normalize.scan (rules.get i).normalize.capital.wager (fun _ => V) 0 X) + ∂cond (PrefixStage.law old n) C.event) + + cond (PrefixStage.law old n) C.event + (LateDropBound.partialEvent C (rules.get i).normalize.scan V) ≤ + ENNReal.ofReal (4 * (error : ℝ)) + tail : ∀ i : Fin rules.length, + cond (PrefixStage.law old n) C.event + (StoppingTranscript.rankDropTailEvent C (rules.get i).normalize.scan V) ≤ + ENNReal.ofReal (2 * (error : ℝ)) + high : ∀ i : Fin rules.length, + PrefixStage.law old n ((rules.get i).normalize.scan.observationMap ⁻¹' H i ∩ + NoDrop.noDropEvent C (rules.get i).normalize.scan) ≤ ENNReal.ofReal (error : ℝ) + low : ∀ a ≤ n, ∀ i : Fin rules.length, + PrefixStage.law old a (StagePreHorizon.lowDropInput (rules.get i) (H i) C) ≤ + ENNReal.ofReal (error : ℝ) + +/-- The fully represented output of one successful stage. -/ +structure Result (old : ℕ → AffineBlock) (n : ℕ) (rules : List BettingStrategy) + (H : Fin rules.length → Set Cantor) (error : ℚ) (r level : ℕ) (G : List ℕ) where + /-- The selected affine constraint to impose at this stage. -/ + block : AffineBlock + /-- The query horizon protected by this step. -/ + horizon : ℕ + /-- The finite description of the selected affine constraint. -/ + code : AffineCode.Data + /-- The short bit string that runs to the affine code. -/ + program : List Bool + valid : AffineCode.valid code = true + runs : code ∈ AffineDescription.run program + code_rank : AffineCode.rank code = r + block_rank : block.rank = r + event_eq : AffineCode.event code = block.event + budget : 2 * program.length + level + 1 ≤ r + support_subset : block.support ⊆ G.toFinset + bounds : Bounds old n rules H error block horizon + +/-- The input form of the low-drop event agrees with the rank-event API. -/ +theorem lowDropInput_eq (s : BettingStrategy) (H : Set Cantor) (C : AffineBlock) : + StagePreHorizon.lowDropInput s H C = + s.normalize.scan.observationMap ⁻¹' Hᶜ ∩ LateDropBound.hasDrop C s.normalize.scan := by + simp only [StagePreHorizon.lowDropInput, Set.preimage_inter, Set.preimage_compl, + NoDrop.observationMap_preimage_noDropTranscripts, LateDropBound.hasDrop] + +/-- The input form of the high missed-pool event agrees with the horizon API. -/ +theorem highMissInput_eq (s : BettingStrategy) (H : Set Cantor) (G : List ℕ) : + StagePreHorizon.highMissInput s H G = + s.normalize.scan.observationMap ⁻¹' H ∩ + {X | 0 < PoolQuery.missedCount s.normalize.scan G.toFinset + (s.normalize.scan.observationMap X)} := by + ext X + simp only [StagePreHorizon.highMissInput, Set.mem_preimage, StagePreHorizon.highPoolMiss, + Set.mem_ofPred_eq, Set.mem_inter_iff, PoolQuery.missedCount_pos_iff, List.mem_toFinset] + +/-- Changing the syndrome preserves the low-drop input event. -/ +@[simp] theorem lowDropInput_withSyndrome (s : BettingStrategy) (H : Set Cantor) + (C : AffineBlock) (y : Fin C.rank → ZMod 2) : + StagePreHorizon.lowDropInput s H (StageSyndrome.withSyndrome C y) = + StagePreHorizon.lowDropInput s H C := rfl + +/-- A positive-rank block with no drop must have an unread coordinate in +any containing pool. Hence its high no-drop event is covered by the same +high-miss event already bounded before horizon selection. -/ +theorem high_noDrop_subset_highMiss (s : BettingStrategy) (H : Set Cantor) + (C : AffineBlock) (G : List ℕ) (hCG : C.support ⊆ G.toFinset) (hr : 0 < C.rank) : + s.normalize.scan.observationMap ⁻¹' H ∩ NoDrop.noDropEvent C s.normalize.scan ⊆ + StagePreHorizon.highMissInput s H G := by + rw [highMissInput_eq] + intro X hX + refine ⟨hX.1, ?_⟩ + have hz : s.normalize.scan.observationMap X ∈ + NoDrop.noDropTranscripts C s.normalize.scan := by + change X ∈ s.normalize.scan.observationMap ⁻¹' NoDrop.noDropTranscripts C s.normalize.scan + rw [NoDrop.observationMap_preimage_noDropTranscripts] + exact hX.2 + exact StageRank.noDropTranscripts_subset_missed C s.normalize.scan G.toFinset hCG hr hz + +/-- The support of every concrete embedded candidate lies in the output pool. -/ +theorem block_support_subset (G : List ℕ) (hG : G.Nodup) {m r : ℕ} + (a : SparseListSearch.Entry) (ha : SparseListSearch.GoodEntry G.length m r a) + (y : Fin r → ZMod 2) : + (StageCandidate.block G.get hG.injective_get a ha y).support ⊆ G.toFinset := by + intro p hp + obtain ⟨j, _, rfl⟩ := Finset.mem_image.mp hp + exact List.mem_toFinset.mpr (List.get_mem _ _) + +/-- The block produced by the finite syndrome minimizer. -/ +def chosenBlock (rules : List BettingStrategy) (cs : List AffineCode.Data) + (G : List ℕ) (hG : G.Nodup) {m r : ℕ} (a : SparseListSearch.Entry) + (ha : SparseListSearch.GoodEntry G.length m r a) (V : ℕ) : AffineBlock := + StageCandidate.block G.get hG.injective_get a ha + (SparseSearch.wordVector r (StageSyndromeObjective.chosen rules cs G a V)) + +@[simp] theorem withSyndrome_block (G : List ℕ) (hG : G.Nodup) {m r : ℕ} + (a : SparseListSearch.Entry) (ha : SparseListSearch.GoodEntry G.length m r a) + (y z : Fin r → ZMod 2) : + StageSyndrome.withSyndrome (StageCandidate.block G.get hG.injective_get a ha y) z = + StageCandidate.block G.get hG.injective_get a ha z := rfl + +end Klr.StageOneStep diff --git a/LeanPool/KLRandomness/StageOneStepHorizon.lean b/LeanPool/KLRandomness/StageOneStepHorizon.lean new file mode 100644 index 0000000000..0ef32faf96 --- /dev/null +++ b/LeanPool/KLRandomness/StageOneStepHorizon.lean @@ -0,0 +1,128 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.StageOneStepBounds +public import LeanPool.KLRandomness.StageRankProbability + +/-! +# The actual horizon search for one selected candidate + +The reconstruction program stores a list of betting strategies. These +lemmas identify its rational rank statistics, computed on the corresponding +list of scans, with the finite-family probabilities in the analytic bounds. +The selected bounded advice therefore makes that very search halt. +-/ + +@[expose] public section + +noncomputable section + +namespace Klr.StageOneStep + +open MeasureTheory SparseListSearch StageCandidate +open scoped BigOperators + +theorem partialSum_map_normalize (rules : List BettingStrategy) + (cs : List AffineCode.Data) (G : List ℕ) (hG : G.Nodup) {m r : ℕ} + (a : Entry) (ha : GoodEntry G.length m r a) (y : Fin r → ZMod 2) (V : ℕ) : + (StageRankProbability.partialSum (rules.map (fun s => s.normalize.scan)) cs G a.2 V : ℝ) = + StageRankLimit.partialMass (StageFiniteProbability.law cs) + (block G.get hG.injective_get a ha y) + (fun i : Fin rules.length => (rules.get i).normalize.scan) V := by + have hsum : StageRankProbability.partialSum (rules.map (fun s => s.normalize.scan)) + cs G a.2 V = ∑ i : Fin rules.length, + StageRankProbability.partialProbability cs (rules.get i).normalize.scan G a.2 V := by + unfold StageRankProbability.partialSum + rw [List.map_map] + conv_lhs => rw [← List.ofFn_get rules, List.map_ofFn, List.sum_ofFn] + rfl + rw [hsum, Rat.cast_sum] + apply Finset.sum_congr rfl + intro i _ + exact StageRankProbability.partialProbability_eq_measureReal + cs (rules.get i).normalize.scan G hG a ha y V + +theorem dropSum_map_normalize (rules : List BettingStrategy) + (cs : List AffineCode.Data) (G : List ℕ) (hG : G.Nodup) {m r : ℕ} + (a : Entry) (ha : GoodEntry G.length m r a) (y : Fin r → ZMod 2) (V : ℕ) : + (StageRankProbability.dropSum (rules.map (fun s => s.normalize.scan)) cs G a.2 V : ℝ) = + StageRankLimit.dropMass (StageFiniteProbability.law cs) + (block G.get hG.injective_get a ha y) + (fun i : Fin rules.length => (rules.get i).normalize.scan) V := by + have hsum : StageRankProbability.dropSum (rules.map (fun s => s.normalize.scan)) + cs G a.2 V = ∑ i : Fin rules.length, + StageRankProbability.dropProbability cs (rules.get i).normalize.scan G a.2 V := by + unfold StageRankProbability.dropSum + rw [List.map_map] + conv_lhs => rw [← List.ofFn_get rules, List.map_ofFn, List.sum_ofFn] + rfl + rw [hsum, Rat.cast_sum] + apply Finset.sum_congr rfl + intro i _ + exact StageRankProbability.dropProbability_eq_measureReal + cs (rules.get i).normalize.scan G hG a ha y V + +/-- The bounded-advice search used in the actual reconstruction program +returns a horizon with both required old-law estimates. -/ +theorem exists_computed_horizon + (old : ℕ → AffineBlock) + (hold : Pairwise (fun i j => Disjoint (old i).support (old j).support)) + (n : ℕ) (rules : List BettingStrategy) (H : Fin rules.length → Set Cantor) + (cs : List AffineCode.Data) + (hcs : StageFiniteProbability.law cs = PrefixStage.law old n) + (G : List ℕ) (hG : G.Nodup) {m r : ℕ} + (a : Entry) (ha : GoodEntry G.length m r a) + {error : ℚ} (herror : 0 < error) + (hhigh : (∑ i : Fin rules.length, (PrefixStage.law old n).real + (StagePreHorizon.highMissInput (rules.get i) (H i) G)) < (error : ℝ)) + (hlow : (∑ i : Fin rules.length, (PrefixStage.law old n).real + (StagePreHorizon.lowDropInput (rules.get i) (H i) + (block G.get hG.injective_get a ha 0))) < (error : ℝ)) : + ∃ b, b ≤ StageHorizon.adviceBound error rules.length ∧ ∃ V, + V ∈ StageHorizon.search error + (StageRankProbability.u (rules.map (fun s => s.normalize.scan))) + (StageRankProbability.v (rules.map (fun s => s.normalize.scan))) + (((cs, G), a.2), b) ∧ + StageRankLimit.partialMass (PrefixStage.law old n) + (block G.get hG.injective_get a ha 0) + (fun i : Fin rules.length => (rules.get i).normalize.scan) V < 3 * (error : ℝ) ∧ + (∑ i : Fin rules.length, (PrefixStage.law old n).real + (StoppingTranscript.rankDropTailEvent (block G.get hG.injective_get a ha 0) + (rules.get i).normalize.scan V)) < 2 * (error : ℝ) := by + let : IsProbabilityMeasure (PrefixStage.law old n) := + PrefixStage.law_isProbabilityMeasure old hold n + have hu (V : ℕ) : + (StageRankProbability.u (rules.map (fun s => s.normalize.scan)) ((cs, G), a.2) V : ℝ) = + StageRankLimit.partialMass (PrefixStage.law old n) + (block G.get hG.injective_get a ha 0) + (fun i : Fin rules.length => (rules.get i).normalize.scan) V := by + simpa only [StageRankProbability.u, hcs] using + partialSum_map_normalize rules cs G hG a ha 0 V + have hv (V : ℕ) : + (StageRankProbability.v (rules.map (fun s => s.normalize.scan)) ((cs, G), a.2) V : ℝ) = + StageRankLimit.dropMass (PrefixStage.law old n) + (block G.get hG.injective_get a ha 0) + (fun i : Fin rules.length => (rules.get i).normalize.scan) V := by + simpa only [StageRankProbability.v, hcs] using + dropSum_map_normalize rules cs G hG a ha 0 V + obtain ⟨b, hb, hdom, hspec⟩ := + StageRankLimit.exists_bounded_advice_search_of_rank_probabilities herror + ((cs, G), a.2) (PrefixStage.law old n) (block G.get hG.injective_get a ha 0) + (fun i : Fin rules.length => (rules.get i).normalize.scan) + G.toFinset (block_support_subset G hG a ha 0) H hu hv + (by simpa only [highMissInput_eq] using hhigh) + (by simpa only [lowDropInput_eq] using hlow) + obtain ⟨V, hV⟩ := Part.dom_iff_mem.mp hdom + obtain ⟨haccepted, htail⟩ := hspec V hV + refine ⟨b, by simpa only [Fintype.card_fin] using hb, V, hV, ?_, htail⟩ + rw [← hu V] + exact_mod_cast haccepted.1 + +end Klr.StageOneStep diff --git a/LeanPool/KLRandomness/StagePreHorizon.lean b/LeanPool/KLRandomness/StagePreHorizon.lean new file mode 100644 index 0000000000..d87b0fd359 --- /dev/null +++ b/LeanPool/KLRandomness/StagePreHorizon.lean @@ -0,0 +1,217 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.StageChoice +import Mathlib.Tactic.Linarith +import Mathlib.Tactic.Positivity +import Mathlib.Tactic.Ring + +/-! +# A genuine stage candidate before choosing a horizon + +The Borel high sets are fixed once for the full scan family. At one stage, +a positive rational error, a rational density, and a pool-producing program +are fixed before the trial rank varies. For all sufficiently large ranks, +the actual pool program and the actual sparse-list construction both halt. +One list entry then has small wager and low-rank-drop costs simultaneously. +The bounds hold for every subsequent syndrome and every earlier stage law. +-/ + +@[expose] public section + +namespace Klr.StagePreHorizon + +open Filter MeasureTheory StageChoice +open scoped BigOperators Topology + +/-- The high-part event that at least one position of the actual pool is +never queried on the complete prescribed answer sequence. -/ +def highPoolMiss (π : ScanRule) (H : Set Cantor) (G : List ℕ) : Set Cantor := + {Z | Z ∈ H ∧ ∃ b ∈ G, ¬ PoolQuery.Reads π b Z} + +theorem measurableSet_highPoolMiss (π : ScanRule) (H : Set Cantor) + (hH : MeasurableSet H) (G : List ℕ) : MeasurableSet (highPoolMiss π H G) := by + have he : highPoolMiss π H G = + H ∩ {Z | (0 : ℝ) < (PoolQuery.missedCount π G.toFinset Z : ℝ)} := by + ext Z + simp [highPoolMiss, PoolQuery.missedCount_pos_iff] + rw [he] + exact hH.inter (measurableSet_lt measurable_const (StageRank.measurable_missedCount_real π _)) + +/-- A low-part rank drop pulled back from answers to the actual input. -/ +noncomputable def lowDropInput (s : BettingStrategy) (H : Set Cantor) + (C : AffineBlock) : Set Cantor := + s.normalize.scan.observationMap ⁻¹' + (Hᶜ ∩ (NoDrop.noDropTranscripts C s.normalize.scan)ᶜ) + +/-- A high-part missed pool pulled back to the actual input. -/ +noncomputable def highMissInput (s : BettingStrategy) (H : Set Cantor) (G : List ℕ) : Set Cantor := + s.normalize.scan.observationMap ⁻¹' highPoolMiss s.normalize.scan H G + +/-- Embed the selected executable entry in the concrete output pool. -/ +noncomputable def candidate {τ θ : ℚ} {r : ℕ} {G : List ℕ} + {L : SparseListSearch.CodeList} (hGM : G.length = SparseParameters.blockSize r) + (hG : G.Nodup) (hL : L ∈ SparseListConstruction.construct τ θ r) + (q : Fin L.length) (y : Fin r → ZMod 2) : AffineBlock := + StageRank.listBlock (SparseListConstruction.construct_spec hL) + (poolLabel G hGM) (poolLabel_injective G hGM hG) (fun _ => y) q + +@[simp] theorem candidate_rank {τ θ : ℚ} {r : ℕ} {G : List ℕ} + {L : SparseListSearch.CodeList} (hGM : G.length = SparseParameters.blockSize r) + (hG : G.Nodup) (hL : L ∈ SparseListConstruction.construct τ θ r) + (q : Fin L.length) (y : Fin r → ZMod 2) : + (candidate hGM hG hL q y).rank = r := rfl + +theorem candidate_support_subset {τ θ : ℚ} {r : ℕ} {G : List ℕ} + {L : SparseListSearch.CodeList} (hGM : G.length = SparseParameters.blockSize r) + (hG : G.Nodup) (hL : L ∈ SparseListConstruction.construct τ θ r) + (q : Fin L.length) (y : Fin r → ZMod 2) : + (candidate hGM hG hL q y).support ⊆ G.toFinset := by + rw [← poolLabel_image_univ G hGM] + change (SparseListWeights.support (SparseParameters.blockSize r) (L.get q)).image + (poolLabel G hGM) ⊆ _ + exact Finset.image_subset_image (Finset.subset_univ _) + +/-- A strict joint score controls the entire protected sum under each old +law; no extra factor for the number of scans is lost in this step. -/ +theorem sums_lt_of_joint_score (s : ℕ → BettingStrategy) (H : ℕ → Set Cantor) + (hH : ∀ i, MeasurableSet (H i)) (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) + (n : ℕ) (C : AffineBlock) {ε : ℝ} + (hscore : (∑ i : Fin (n + 1), + (wagerCost (PrefixStage.law B n) (s i) C + + (2 : ℝ) ^ (∑ k : Fin n, (B k).rank) * lowDropCost (H i)ᶜ (s i) C)) < ε) : + (∑ i : Fin (n + 1), wagerCost (PrefixStage.law B n) (s i) C) < ε ∧ + ∀ a ≤ n, (∑ i : Fin (n + 1), + (PrefixStage.law B a).real (lowDropInput (s i) (H i) C)) < ε := by + constructor + · apply lt_of_le_of_lt _ hscore + exact Finset.sum_le_sum fun i _ => + le_add_of_nonneg_right (mul_nonneg (by positivity) (lowDropCost_nonneg _ _ _)) + · intro a ha + apply lt_of_le_of_lt _ hscore + apply Finset.sum_le_sum + intro i _ + exact (prefixLaw_observationReal_le B hdis n a ha (s i).normalize.scan _ + ((hH i).compl.inter (NoDrop.measurableSet_noDropTranscripts _ _).compl)).trans + (le_add_of_nonneg_left (wagerCost_nonneg _ _ _)) + +/-- Good pools control the protected high-part missed-pool sum under every +earlier conditional law, with the same prefix-rank density factor. -/ +theorem highMiss_sum_lt_of_goodPool (s : ℕ → BettingStrategy) (H : ℕ → Set Cantor) + (hH : ∀ i, MeasurableSet (H i)) (B : ℕ → AffineBlock) + (hdis : Pairwise (fun i j => Disjoint (B i).support (B j).support)) + (n : ℕ) {z M : ℕ} {τ : ℚ} {η : ℝ} {G : List ℕ} + (hG : PoolConstruction.GoodPool (fun i => (s i).normalize.scan) H (n + 1) η z τ M G) + (a : ℕ) (ha : a ≤ n) : + (∑ i : Fin (n + 1), (PrefixStage.law B a).real (highMissInput (s i) (H i) G)) < + ((n + 1 : ℕ) : ℝ) * (2 : ℝ) ^ (∑ k : Fin n, (B k).rank) * η := by + have hsum : (∑ i : Fin (n + 1), fairCoin.real (highPoolMiss (s i).normalize.scan (H i) G)) < + ((n + 1 : ℕ) : ℝ) * η := by + simpa only [highPoolMiss, Finset.sum_const, Finset.card_univ, Fintype.card_fin, + nsmul_eq_mul] using + Finset.sum_lt_sum_of_nonempty (s := (Finset.univ : Finset (Fin (n + 1)))) + Finset.univ_nonempty (fun i _ => (hG.2.2.2 i i.isLt).1) + calc + _ ≤ ∑ i : Fin (n + 1), + (2 : ℝ) ^ (∑ k : Fin n, (B k).rank) * + fairCoin.real (highPoolMiss (s i).normalize.scan (H i) G) := + Finset.sum_le_sum fun i _ => + prefixLaw_observationReal_le B hdis n a ha (s i).normalize.scan _ + (measurableSet_highPoolMiss _ _ (hH i) G) + _ = (2 : ℝ) ^ (∑ k : Fin n, (B k).rank) * + ∑ i : Fin (n + 1), fairCoin.real (highPoolMiss (s i).normalize.scan (H i) G) := + (Finset.mul_sum _ _ _).symm + _ < (2 : ℝ) ^ (∑ k : Fin n, (B k).rank) * (((n + 1 : ℕ) : ℝ) * η) := + mul_lt_mul_of_pos_left hsum (by positivity) + _ = _ := by ring + +/-- Pool sizes tend to infinity along the paper's rank parameter. -/ +theorem tendsto_blockSize_nat : Tendsto SparseParameters.blockSize atTop atTop := by + exact tendsto_pow_atTop (α := ℕ) (by decide : 8 ≠ 0) + +/-- Fixed partitions, fixed rational thresholds and one fixed pool program +produce actual stage candidates at every sufficiently large trial rank. + +The index is shorter than `r^24`, and all estimates hold for every syndrome +chosen later. The protected family is exactly the first `n + 1` strategies. -/ +theorem exists_fixed_partitions_eventual_candidates (s : ℕ → BettingStrategy) : + ∃ H : ℕ → Set Cantor, (∀ i, MeasurableSet (H i)) ∧ + ∀ (B : ℕ → AffineBlock), + Pairwise (fun i j => Disjoint (B i).support (B j).support) → + ∀ (n z : ℕ) (ε : ℝ), 0 < ε → + ∃ η : ℚ, 0 < η ∧ + ((n + 1 : ℕ) : ℝ) * (2 : ℝ) ^ (∑ k : Fin n, (B k).rank) * + ((η : ℝ) + η) < ε / 2 ∧ + ∃ τ : ℚ, 0 < τ ∧ τ < 1 / 4 ∧ + ∃ e : Nat.Partrec.Code, ∀ᶠ r : ℕ in atTop, + ∃ (G : List ℕ) (L : SparseListSearch.CodeList) + (hG : PoolConstruction.GoodPool (fun i => (s i).normalize.scan) + H (n + 1) (η : ℝ) z τ (SparseParameters.blockSize r) G) + (hL : L ∈ SparseListConstruction.construct τ η r), + PoolAdvice.encodePool G ∈ e.eval (SparseParameters.blockSize r) ∧ + ∃ q : Fin L.length, 0 < r ∧ q.val < r ^ 24 ∧ + (∀ a ≤ n, (∑ i : Fin (n + 1), + (PrefixStage.law B a).real (highMissInput (s i) (H i) G)) < ε) ∧ + ∀ y : Fin r → ZMod 2, + (∑ i : Fin (n + 1), wagerCost (PrefixStage.law B n) (s i) + (candidate hG.1 hG.2.1 hL q y)) < ε ∧ + ∀ a ≤ n, (∑ i : Fin (n + 1), (PrefixStage.law B a).real + (lowDropInput (s i) (H i) (candidate hG.1 hG.2.1 hL q y))) < ε := by + obtain ⟨H, hH, hpool⟩ := PoolConstruction.exists_fixed_partitions_computable_pools + (fun i => (s i).normalize.scan) + refine ⟨H, hH, ?_⟩ + intro B hdis n z ε hε + let d : ℝ := (2 : ℝ) ^ (∑ k : Fin n, (B k).rank) + let c : ℝ := ((n + 1 : ℕ) : ℝ) * d + have hd : 0 < d := by dsimp [d]; positivity + have hc : 0 < c := by dsimp [c]; positivity + obtain ⟨η, hη0, hηsmall⟩ := exists_rat_btwn (show (0 : ℝ) < ε / (4 * c) by positivity) + have hη : (0 : ℚ) < η := by exact_mod_cast hη0 + have hsmall : c * (η : ℝ) < ε / 4 := by + have ht := (lt_div_iff₀ (show (0 : ℝ) < 4 * c by positivity)).mp hηsmall + nlinarith + have hbudget : c * ((η : ℝ) + η) < ε / 2 := by nlinarith + have hhigh : c * (η : ℝ) < ε := hsmall.trans (by linarith) + obtain ⟨τ, hτ, hτquarter, e, he⟩ := hpool (n + 1) (η : ℝ) hη0 z + refine ⟨η, hη, hbudget, τ, hτ, hτquarter, e, ?_⟩ + have hpools := tendsto_blockSize_nat.eventually he + have hlists := SparseListConstruction.eventually_construct_good τ η hτ hη + have hwager := StageWeights.eventually_family_supportWager_bound_lt (n + 1) + (show 0 < ε / 2 by positivity) + filter_upwards [hpools, hlists, hwager, eventually_ge_atTop 1] with r hpr hlr hwr hr + obtain ⟨G, hGeval, hG⟩ := hpr + obtain ⟨L, hL, hgood⟩ := hlr + have hrpos : 0 < r := hr + have hJ : 0 < SparseParameters.listSize r := by + unfold SparseParameters.listSize SparseParameters.blockSize + positivity + let := PrefixStage.law_isProbabilityMeasure B hdis n + obtain ⟨q, hq⟩ := exists_candidate_joint_bound_of_goodPool (PrefixStage.law B n) + hgood hJ hη.le s H (fun i _ => hH i) (η : ℝ) hG (fun _ _ => 0) hd.le + have hscore : (∑ i : Fin (n + 1), + (wagerCost (PrefixStage.law B n) (s i) (candidate hG.1 hG.2.1 hL q 0) + + d * lowDropCost (H i)ᶜ (s i) (candidate hG.1 hG.2.1 hL q 0))) < ε := by + apply lt_of_le_of_lt hq + rw [StageWeights.polynomial_supportWager_bound_eq] + dsimp [c] at hbudget + nlinarith + refine ⟨G, L, hG, hL, hGeval, q, hrpos, ?_, ?_, ?_⟩ + · have hlen : L.length = r ^ 24 := by + rw [hgood.1] + simp only [SparseParameters.listSize, SparseParameters.blockSize, ← pow_mul] + exact q.isLt.trans_eq hlen + · intro a ha + exact (highMiss_sum_lt_of_goodPool s H hH B hdis n hG a ha).trans hhigh + · intro y + apply sums_lt_of_joint_score s H hH B hdis n + exact hscore + +end Klr.StagePreHorizon diff --git a/LeanPool/KLRandomness/StagePrefixCode.lean b/LeanPool/KLRandomness/StagePrefixCode.lean new file mode 100644 index 0000000000..eb0735f323 --- /dev/null +++ b/LeanPool/KLRandomness/StagePrefixCode.lean @@ -0,0 +1,105 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.AffineCodeCoverage +public import LeanPool.KLRandomness.StageFiniteProbability +public import LeanPool.KLRandomness.PrefixStage + +/-! +# Finite code headers for the previous affine constraints + +Every finite-support affine block has a valid finite code. We choose those +codes non-effectively for the already constructed blocks and place them in +the fixed stage header. The resulting executable finite-stage law is exactly +the original conditional law. This choice does not claim a computable global +enumeration of the block construction. +-/ + +@[expose] public section + +noncomputable section + +namespace Klr.StagePrefixCode + +/-- A finite valid code for one already fixed affine block. -/ +def code (B : AffineBlock) : AffineCode.Data := + (AffineCode.exists_valid_code_of_affineBlock B).choose + +@[simp] theorem rank_code (B : AffineBlock) : AffineCode.rank (code B) = B.rank := + (AffineCode.exists_valid_code_of_affineBlock B).choose_spec.1 + +@[simp] theorem valid_code (B : AffineBlock) : AffineCode.valid (code B) = true := + (AffineCode.exists_valid_code_of_affineBlock B).choose_spec.2.1 + +@[simp] theorem event_code (B : AffineBlock) : AffineCode.event (code B) = B.event := + (AffineCode.exists_valid_code_of_affineBlock B).choose_spec.2.2 + +/-- The fixed finite header for a finite ordered family of earlier blocks. -/ +def header {n : ℕ} (old : Fin n → AffineBlock) : List AffineCode.Data := + List.ofFn fun i => code (old i) + +@[simp] theorem length_header {n : ℕ} (old : Fin n → AffineBlock) : + (header old).length = n := List.length_ofFn + +theorem valid_of_mem_header {n : ℕ} (old : Fin n → AffineBlock) + {c : AffineCode.Data} (hc : c ∈ header old) : AffineCode.valid c = true := by + obtain ⟨i, rfl⟩ := List.mem_ofFn.mp hc + exact valid_code (old i) + +/-- No information about the previous constraint event is lost by encoding. -/ +theorem event_header {n : ℕ} (old : Fin n → AffineBlock) : + StageFiniteProbability.event (header old) = AffineBlock.familyEvent old := by + ext X + constructor + · intro h i + have hi := h _ (List.mem_ofFn.mpr ⟨i, rfl⟩) + rwa [event_code] at hi + · intro h c hc + obtain ⟨i, rfl⟩ := List.mem_ofFn.mp hc + rw [event_code] + exact h i + +/-- The executable finite header represents the actual old conditional law. -/ +theorem law_header {n : ℕ} (old : Fin n → AffineBlock) : + StageFiniteProbability.law (header old) = AffineBlock.finiteStageLaw old := by + unfold StageFiniteProbability.law AffineBlock.finiteStageLaw + rw [event_header] + +theorem sum_rank_header {n : ℕ} (old : Fin n → AffineBlock) : + ((header old).map AffineCode.rank).sum = ∑ i, (old i).rank := by + simp only [header, List.map_ofFn, List.sum_ofFn, Function.comp_apply, rank_code] + +/-- The previous prefix of any block sequence has a finite valid header. -/ +def prefixHeader (B : ℕ → AffineBlock) (n : ℕ) : List AffineCode.Data := + header (PrefixStage.prefixFamily B n) + +@[simp] theorem length_prefixHeader (B : ℕ → AffineBlock) (n : ℕ) : + (prefixHeader B n).length = n := length_header _ + +theorem event_prefixHeader (B : ℕ → AffineBlock) (n : ℕ) : + StageFiniteProbability.event (prefixHeader B n) = PrefixStage.prefixEvent B n := + event_header _ + +theorem law_prefixHeader (B : ℕ → AffineBlock) (n : ℕ) : + StageFiniteProbability.law (prefixHeader B n) = PrefixStage.law B n := + law_header _ + +/-- The finite old data can always be fixed before the trial rank. Neither +pairwise disjointness nor effectiveness of the infinite sequence is needed +for the representation itself. -/ +theorem exists_prefix_header (B : ℕ → AffineBlock) (n : ℕ) : + ∃ cs : List AffineCode.Data, cs.length = n ∧ + (∀ c ∈ cs, AffineCode.valid c = true) ∧ + StageFiniteProbability.event cs = PrefixStage.prefixEvent B n ∧ + StageFiniteProbability.law cs = PrefixStage.law B n := + ⟨prefixHeader B n, length_prefixHeader B n, fun _ hc => valid_of_mem_header _ hc, + event_prefixHeader B n, law_prefixHeader B n⟩ + +end Klr.StagePrefixCode diff --git a/LeanPool/KLRandomness/StagePrepared.lean b/LeanPool/KLRandomness/StagePrepared.lean new file mode 100644 index 0000000000..5a8910c700 --- /dev/null +++ b/LeanPool/KLRandomness/StagePrepared.lean @@ -0,0 +1,130 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.StagePreHorizon +public import LeanPool.KLRandomness.StageReconstruction +public import LeanPool.KLRandomness.StageProgramLength +public import LeanPool.KLRandomness.StagePrefixCode + +/-! +# Fixing the program before selecting the final stage rank + +The pool lemma and sparse-list estimates give good candidates at every +sufficiently large rank. The reconstruction compiler gives one fixed code +before the rank is selected, and the explicit pairing estimate gives another +eventual bound. Intersecting these two eventual sets chooses an actual +candidate meeting the short-description budget for every allowed horizon +advice. The Borel partitions are fixed before any stage data. +-/ + +@[expose] public section + +noncomputable section + +namespace Klr.StagePrepared + +open Filter MeasureTheory SparseListSearch +open scoped BigOperators + +/-- The finite protected strategy list in the fixed program header. -/ +def protectedRules (s : ℕ → BettingStrategy) (n : ℕ) : List BettingStrategy := + List.ofFn (fun i : Fin (n + 1) => s i) + +@[simp] theorem length_protectedRules (s : ℕ → BettingStrategy) (n : ℕ) : + (protectedRules s n).length = n + 1 := List.length_ofFn + +/-- Concrete outputs and estimates selected at a rank large enough for the +already fixed reconstruction program. The syndrome remains to be computed. -/ +structure Prepared (s : ℕ → BettingStrategy) (H : ℕ → Set Cantor) + (old : ℕ → AffineBlock) (n z : ℕ) (error : ℚ) where + /-- The rational tolerance used for the sparse-candidate bounds. -/ + listError : ℚ + /-- The density threshold for testing candidate restrictions. -/ + density : ℚ + listError_pos : 0 < listError + density_pos : 0 < density + density_lt : density < 1 / 4 + /-- The fixed program that computes a pool from its finite input parameters. -/ + poolProgram : Nat.Partrec.Code + /-- The fixed reconstruction program used to describe a selected affine constraint. -/ + program : Nat.Partrec.Code + /-- The rank selected for the new affine constraint. -/ + rank : ℕ + /-- The finite list of fresh positions selected for this stage. -/ + pool : List ℕ + /-- The coded list of sparse candidate affine constraints on the pool. -/ + candidates : CodeList + goodPool : PoolConstruction.GoodPool (fun i => (s i).normalize.scan) + H (n + 1) (listError : ℝ) z density (SparseParameters.blockSize rank) pool + list_eval : candidates ∈ SparseListConstruction.construct density listError rank + pool_eval : PoolAdvice.encodePool pool ∈ poolProgram.eval (SparseParameters.blockSize rank) + /-- The selected candidate's index in the finite list. -/ + index : Fin candidates.length + rank_pos : 0 < rank + index_lt : index.val < rank ^ 24 + program_correct : ∀ r q b, + AffineDescription.run (AffineDescription.programFor program (Nat.pair r (Nat.pair q b))) = + StageReconstruction.run (protectedRules s n) (StagePrefixCode.prefixHeader old n) + poolProgram error density listError (r, (q, b)) + program_budget : ∀ b, b ≤ StageHorizon.adviceBound error (n + 1) → + 2 * (AffineDescription.programFor program (Nat.pair rank (Nat.pair index.val b))).length + + n + 1 ≤ rank + high_miss : ∀ a ≤ n, (∑ i : Fin (n + 1), + (PrefixStage.law old a).real (StagePreHorizon.highMissInput (s i) (H i) pool)) < error + scores : ∀ y : Fin rank → ZMod 2, + (∑ i : Fin (n + 1), StageChoice.wagerCost (PrefixStage.law old n) (s i) + (StagePreHorizon.candidate goodPool.1 goodPool.2.1 list_eval index y)) < error ∧ + ∀ a ≤ n, (∑ i : Fin (n + 1), (PrefixStage.law old a).real + (StagePreHorizon.lowDropInput (s i) (H i) + (StagePreHorizon.candidate goodPool.1 goodPool.2.1 list_eval index y))) < error + +/-- The entire finite-stage preparation exists without an effectiveness +assumption on the infinite sequence of stages or the enumeration of strategies. -/ +theorem exists_fixed_partitions_prepared (s : ℕ → BettingStrategy) : + ∃ H : ℕ → Set Cantor, (∀ i, MeasurableSet (H i)) ∧ + ∀ (old : ℕ → AffineBlock), + Pairwise (fun i j => Disjoint (old i).support (old j).support) → + ∀ (n z : ℕ) (error : ℚ), 0 < error → + Nonempty (Prepared s H old n z error) := by + obtain ⟨H, hH, hstage⟩ := StagePreHorizon.exists_fixed_partitions_eventual_candidates s + refine ⟨H, hH, ?_⟩ + intro old hold n z error he + have heR : (0 : ℝ) < error := by exact_mod_cast he + obtain ⟨η, hη, _, τ, hτ, hτlt, poolProgram, heventually⟩ := + hstage old hold n z (error : ℝ) heR + obtain ⟨program, hprogram⟩ := StageReconstruction.exists_fixed_program + (protectedRules s n) (StagePrefixCode.prefixHeader old n) poolProgram error τ η + have hlength := StageProgramLength.eventually_programFor_stage_budget + program (StageHorizon.adviceBound error (n + 1)) n + obtain ⟨r, hr, hbudget⟩ := (heventually.and hlength).exists + obtain ⟨G, L, hG, hL, hGeval, q, hrpos, hq, hhigh, hscores⟩ := hr + exact ⟨{ + listError := η + density := τ + listError_pos := hη + density_pos := hτ + density_lt := hτlt + poolProgram := poolProgram + program := program + rank := r + pool := G + candidates := L + goodPool := hG + list_eval := hL + pool_eval := hGeval + index := q + rank_pos := hrpos + index_lt := hq + program_correct := hprogram + program_budget := fun b hb => hbudget q.val b hq hb + high_miss := hhigh + scores := hscores }⟩ + +end Klr.StagePrepared diff --git a/LeanPool/KLRandomness/StagePreparedIndex.lean b/LeanPool/KLRandomness/StagePreparedIndex.lean new file mode 100644 index 0000000000..b349b22c16 --- /dev/null +++ b/LeanPool/KLRandomness/StagePreparedIndex.lean @@ -0,0 +1,37 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.StagePrepared + +/-! +# Indices of the finite protected strategy list + +The executable header lists exactly strategies `0, ..., n`. These lemmas +identify its list indices and finite sums with the corresponding stage indices. +-/ + +@[expose] public section + +namespace Klr.StagePrepared + +open scoped BigOperators + +theorem get_protectedRules (s : ℕ → BettingStrategy) (n : ℕ) + (i : Fin (protectedRules s n).length) : + (protectedRules s n).get i = s i.val := by + exact List.get_ofFn (fun j : Fin (n + 1) => s j.val) i + +@[simp] theorem sum_protectedRules {α : Type*} [AddCommMonoid α] + (s : ℕ → BettingStrategy) (n : ℕ) (f : ℕ → α) : + (∑ i : Fin (protectedRules s n).length, f i.val) = + ∑ i : Fin (n + 1), f i.val := by + rw [length_protectedRules] + +end Klr.StagePrepared diff --git a/LeanPool/KLRandomness/StageProgramLength.lean b/LeanPool/KLRandomness/StageProgramLength.lean new file mode 100644 index 0000000000..b86931d74f --- /dev/null +++ b/LeanPool/KLRandomness/StageProgramLength.lean @@ -0,0 +1,55 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.AffineProgramLength + +/-! +# Short descriptions for the complete fixed-stage program + +The variable input is the nested pair of a trial rank, a candidate index +below `r^24`, and bounded horizon advice. The bound on the horizon advice +is fixed before the trial rank. Its binary size therefore contributes only +to the constant term, while the candidate index contributes a multiple of +the rank's binary size. +-/ + +@[expose] public section + +namespace Klr.StageProgramLength + +open Filter AffineDescription AffineProgramLength + +/-- Exact encoding-size estimate for the three variable stage parameters. -/ +theorem size_input_le (B r q b : ℕ) (hq : q < r ^ 24) (hb : b ≤ B) : + Nat.size (Nat.pair r (Nat.pair q b)) ≤ + 96 * Nat.size r + 4 * Nat.size B + 4 := by + have hqsize := (Nat.size_le_size hq.le).trans (size_pow_le r 24) + have hbsize := Nat.size_le_size hb + have hinner := size_pair_le q b + have hmax : max (Nat.size q) (Nat.size b) ≤ + 24 * Nat.size r + Nat.size B + 1 := max_le (by omega) (by omega) + have hinner' : Nat.size (Nat.pair q b) ≤ + 48 * Nat.size r + 2 * Nat.size B + 2 := by omega + have houter := size_pair_le r (Nat.pair q b) + have hmax' : max (Nat.size r) (Nat.size (Nat.pair q b)) ≤ + 48 * Nat.size r + 2 * Nat.size B + 2 := max_le (by omega) hinner' + omega + +/-- One fixed reconstruction program eventually has enough rank to pay +for every possible candidate index and every bounded horizon advice value. -/ +theorem eventually_programFor_stage_budget (e : Nat.Partrec.Code) (B level : ℕ) : + ∀ᶠ r : ℕ in atTop, ∀ q b : ℕ, q < r ^ 24 → b ≤ B → + 2 * (programFor e (Nat.pair r (Nat.pair q b))).length + level + 1 ≤ r := by + filter_upwards [eventually_programFor_length_budget e 96 (4 * Nat.size B + 4) level] + with r hr + intro q b hq hb + exact hr _ (by simpa [Nat.add_assoc] using size_input_le B r q b hq hb) + +end Klr.StageProgramLength diff --git a/LeanPool/KLRandomness/StageRank.lean b/LeanPool/KLRandomness/StageRank.lean new file mode 100644 index 0000000000..bb28c44e03 --- /dev/null +++ b/LeanPool/KLRandomness/StageRank.lean @@ -0,0 +1,262 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.StageCandidate +public import LeanPool.KLRandomness.PoolCoverage +public import LeanPool.KLRandomness.PoolAdviceMeasure + +/-! +# Actual unread coordinates and sparse-candidate rank + +The unread mask is formed from the complete prescribed answer sequence. +If the executable rank test accepts that mask, every finite answer prefix +retains full unread rank. Conversely, a positive-rank block cannot retain +full unread rank after all of its pool has been queried. +-/ + +@[expose] public section + +noncomputable section + +namespace Klr.StageRank + +open SparseListSearch SparseListWeights SparseSearch SparseListCode +open StageCandidate RandomMatrix AffineObservation PoolQuery +open scoped BigOperators + +variable {M m r : ℕ} + +theorem extendUnread_apply_of_mem {ι : Type*} (O : Set ι) [DecidablePred (· ∈ O)] + (x : {i // i ∉ O} → ZMod 2) (p : ι) (hp : p ∈ O) : + extendUnread O x p = 0 := by + change (if h : p ∈ O then 0 else x ⟨p, h⟩) = 0 + exact dite_eq_left hp + +/-- Extending a single unread coordinate gives the corresponding ambient singleton. -/ +theorem unreadMap_single {ι : Type*} [DecidableEq ι] + (D : (ι → ZMod 2) →ₗ[ZMod 2] (Fin r → ZMod 2)) + (O : Set ι) [DecidablePred (· ∈ O)] (p : ι) (hp : p ∉ O) : + unreadMap D O (Pi.single (⟨p, hp⟩ : {i // i ∉ O}) 1) = D (Pi.single p 1) := by + apply congrArg D + ext i + by_cases hi : i = p + · subst i + simp [extendUnread, hp] + · by_cases hO : i ∈ O + · simp [extendUnread, hO, hi] + · have hs : (⟨i, hO⟩ : {i // i ∉ O}) ≠ ⟨p, hp⟩ := + fun h => hi (congrArg Subtype.val h) + simp [extendUnread, hO, hi, hs] + +/-- Full row rank on any unqueried mask guarantees full unread rank of the +actual affine block. Columns outside the candidate support are genuinely zero. -/ +theorem unreadFullRank_of_maskedFullRank + (e : Fin M → ℕ) (he : Function.Injective e) (a : Entry) + (ha : GoodEntry M m r a) (y : Fin r → ZMod 2) + (π : ScanRule) (v : List Bool) (d : List Bool) + (hd : maskedFullRank a.2 d = true) + (hunread : ∀ j : Fin M, d.getD j.val false = true → + e j ∉ π.queriedPositions v) : + (block e he a ha y).UnreadFullRank π v := by + classical + let B := block e he a ha y + let U := unreadMap B.matrix (B.observed π v) + have hcol : ∀ j : maskSet M d, columns a M r j.val ∈ LinearMap.range U := by + intro j + by_cases hj : j.val ∈ support M a + · let p : B.support := positionEquiv e he a ⟨j.val, hj⟩ + have hp : p ∉ B.observed π v := + hunread j.val ((mem_maskSet M d j.val).mp j.property) + refine ⟨Pi.single (⟨p, hp⟩ : {p : B.support // p ∉ B.observed π v}) 1, ?_⟩ + change unreadMap B.matrix (B.observed π v) _ = _ + exact (unreadMap_single B.matrix (B.observed π v) p hp).trans + (block_matrix_single e he a ha y ⟨j.val, hj⟩) + · rw [columns_zero_off_support ha hj] + exact (LinearMap.range U).zero_mem + intro z + obtain ⟨x, hx⟩ := masked_columns_surjective ha d hd z + have hz : z ∈ LinearMap.range U := by + rw [← hx] + change (∑ j : maskSet M d, x j • columns a M r j.val) ∈ LinearMap.range U + exact (LinearMap.range U).sum_mem fun j _ => + (LinearMap.range U).smul_mem (x j) (hcol j) + exact hz + +/-- The finite unread pool mask after one specified answer transcript. -/ +def unreadPool (e : Fin M → ℕ) (π : ScanRule) (v : List Bool) : Finset (Fin M) := + Finset.univ.filter fun j => e j ∉ π.queriedPositions v + +@[simp] theorem mem_unreadPool (e : Fin M → ℕ) (π : ScanRule) (v : List Bool) + (j : Fin M) : j ∈ unreadPool e π v ↔ e j ∉ π.queriedPositions v := by + simp [unreadPool] + +/-- The executable rank test on the exact finite unread-pool mask agrees +in both directions with the affine block's unread-rank predicate. -/ +theorem unreadFullRank_iff_maskedFullRank + (e : Fin M → ℕ) (he : Function.Injective e) (a : Entry) + (ha : GoodEntry M m r a) (y : Fin r → ZMod 2) + (π : ScanRule) (v : List Bool) : + (block e he a ha y).UnreadFullRank π v ↔ + maskedFullRank a.2 (mask (unreadPool e π v)) = true := by + classical + constructor + · intro hfull + by_contra hbad + have hn : ¬ Function.Surjective + (restrictedMap (columns a M r) (maskSet M (mask (unreadPool e π v))) + (K := ZMod 2)) := by + exact fun h => hbad ((maskedFullRank_iff_columns_surjective ha _).mpr h) + obtain ⟨φ, hφ, hzero⟩ := (restricted_not_surjective_iff _ _).mp hn + apply hφ + apply LinearMap.ext + intro z + obtain ⟨x, rfl⟩ := hfull z + change φ (∑ j : support M a, + (extendUnread ((block e he a ha y).observed π v) x) + (positionEquiv e he a j) • columns a M r j.val) = 0 + rw [map_sum] + apply Finset.sum_eq_zero + intro j _ + rw [map_smul] + by_cases hj : e j.val ∈ π.queriedPositions v + · have ho : positionEquiv e he a j ∈ (block e he a ha y).observed π v := hj + rw [extendUnread_apply_of_mem _ x _ ho, zero_smul] + · have hmem : j.val ∈ maskSet M (mask (unreadPool e π v)) := by + simpa using hj + have hz : φ (columns a M r j.val) = 0 := congrFun hzero ⟨j.val, hmem⟩ + rw [hz, smul_zero] + · intro h + apply unreadFullRank_of_maskedFullRank e he a ha y π v _ h + intro j hj + rw [getD_mask, decide_eq_true_eq] at hj + exact (mem_unreadPool e π v j).mp hj + +/-- Pool indices never queried on the infinite prescribed answer sequence. -/ +def neverRead (e : Fin M → ℕ) (π : ScanRule) (Z : Cantor) : Finset (Fin M) := by + classical + exact Finset.univ.filter fun j => ¬ Reads π (e j) Z + +@[simp] theorem mem_neverRead (e : Fin M → ℕ) (π : ScanRule) (Z : Cantor) + (j : Fin M) : j ∈ neverRead e π Z ↔ ¬ Reads π (e j) Z := by + classical + simp [neverRead] + +theorem reads_of_mem_queriedPositions (π : ScanRule) (Z : Cantor) (n a : ℕ) + (h : a ∈ π.queriedPositions (ScanRule.inputPrefix Z n)) : Reads π a Z := by + obtain ⟨j, _, hj⟩ := Finset.mem_image.mp h + exact ⟨j.val, by + simpa only [queryAt, PoolAdvice.inputPrefix_take Z + (by simpa using j.isLt.le)] using hj⟩ + +/-- A successful finite rank check on the actual never-read mask prevents +rank drops along every finite prefix of these answers. -/ +theorem noDropTranscripts_of_maskedFullRank + (e : Fin M → ℕ) (he : Function.Injective e) (a : Entry) + (ha : GoodEntry M m r a) (y : Fin r → ZMod 2) + (π : ScanRule) (Z : Cantor) + (hd : maskedFullRank a.2 (mask (neverRead e π Z)) = true) : + Z ∈ NoDrop.noDropTranscripts (block e he a ha y) π := by + intro n + apply unreadFullRank_of_maskedFullRank e he a ha y π _ _ hd + intro j hj hread + have hm : j ∈ neverRead e π Z := by + rw [getD_mask, decide_eq_true_eq] at hj + exact hj + exact (mem_neverRead e π Z j).mp hm + (reads_of_mem_queriedPositions π Z n (e j) hread) + +/-- The cardinality of the actual never-read mask is the pool missed count. -/ +theorem card_neverRead (e : Fin M → ℕ) (he : Function.Injective e) + (π : ScanRule) (Z : Cantor) : + (neverRead e π Z).card = missedCount π (Finset.univ.image e) Z := by + classical + have hset : (neverRead e π Z).image e = + (Finset.univ.image e).filter (fun a => ¬ Reads π a Z) := by + ext a + simp only [Finset.mem_image, mem_neverRead, Finset.mem_filter, + Finset.mem_univ, true_and] + constructor + · rintro ⟨j, hj, rfl⟩ + exact ⟨⟨j, rfl⟩, hj⟩ + · rintro ⟨⟨j, rfl⟩, hj⟩ + exact ⟨j, hj, rfl⟩ + rw [← Finset.card_image_of_injective (neverRead e π Z) he, hset] + rfl + +/-- Once every coordinate of a finite block has been read, the unread rank +cannot remain positive. The horizon may depend on the complete answer sequence. -/ +theorem noDropTranscripts_subset_missed (B : AffineBlock) (π : ScanRule) + (G : Finset ℕ) (hBG : B.support ⊆ G) (hr : 0 < B.rank) : + NoDrop.noDropTranscripts B π ⊆ {Z | 0 < missedCount π G Z} := by + classical + intro Z hZ + by_contra hmiss + have hzero : missedCount π G Z = 0 := Nat.eq_zero_of_not_pos hmiss + have hall := (missedCount_eq_zero_iff π G Z).mp hzero + choose t ht using (fun p : B.support => hall p.val (hBG p.property)) + let N := Finset.univ.sup fun p : B.support => t p + 1 + have hobs : ∀ p : B.support, p ∈ B.observed π (ScanRule.inputPrefix Z N) := by + intro p + have htN : t p < N := lt_of_lt_of_le (Nat.lt_succ_self _) + (Finset.le_sup (f := fun p : B.support => t p + 1) (Finset.mem_univ p)) + change p.val ∈ π.queriedPositions (ScanRule.inputPrefix Z N) + apply Finset.mem_image.mpr + refine ⟨⟨t p, by simpa using htN⟩, Finset.mem_univ _, ?_⟩ + simpa only [queryAt, PoolAdvice.inputPrefix_take Z htN.le] using ht p + let : IsEmpty {p : B.support // p ∉ B.observed π (ScanRule.inputPrefix Z N)} := + ⟨fun p => p.property (hobs p.val)⟩ + have hbound := unread_rank_le B.matrix (B.observed π (ScanRule.inputPrefix Z N)) (hZ N) + have hc : Fintype.card {p : B.support // p ∉ B.observed π (ScanRule.inputPrefix Z N)} = 0 := + Fintype.card_eq_zero + rw [hc] at hbound + exact (Nat.not_lt_of_ge hbound) hr + +/-- The high-part no-drop mass is bounded by the actual high-part pool-miss mass. -/ +theorem measure_high_noDrop_le (B : AffineBlock) (π : ScanRule) + (G : Finset ℕ) (hBG : B.support ⊆ G) (hr : 0 < B.rank) + (H : Set Cantor) (μ : MeasureTheory.Measure Cantor) : + μ (H ∩ NoDrop.noDropTranscripts B π) ≤ + μ {Z | Z ∈ H ∧ 0 < missedCount π G Z} := + MeasureTheory.measure_mono fun _Z hZ => + ⟨hZ.1, noDropTranscripts_subset_missed B π G hBG hr hZ.2⟩ + +/-- Entries are indexed by their list positions, preserving multiplicities. -/ +def listBlock {J : ℕ} {τ θ : ℚ} {L : CodeList} + (hL : Good M m r J τ θ L) (e : Fin M → ℕ) (he : Function.Injective e) + (y : Fin L.length → Fin r → ZMod 2) (j : Fin L.length) : AffineBlock := + block e he (L.get j) (hL.2.1 _ (List.get_mem _ _)) (y j) + +open Classical in +/-- For every complete answer sequence with a dense never-read pool mask, +only the verifier's allowed fraction of candidates can undergo a rank drop. -/ +theorem card_hasDrop_le {J : ℕ} {τ θ : ℚ} {L : CodeList} + (hL : Good M m r J τ θ L) (e : Fin M → ℕ) (he : Function.Injective e) + (y : Fin L.length → Fin r → ZMod 2) (π : ScanRule) (Z : Cantor) + (hdense : τ * (M : ℚ) ≤ ((neverRead e π Z).card : ℚ)) : + ((Finset.univ.filter fun j : Fin L.length => + Z ∉ NoDrop.noDropTranscripts (listBlock hL e he y j) π).card : ℚ) ≤ θ * J := by + classical + let d := mask (neverRead e π Z) + have hbound := hL.2.2.2 d (length_mask _) (by simpa [d] using hdense) + apply le_trans _ hbound + apply Nat.cast_le.mpr + rw [countP_eq_card_filter_get] + apply Finset.card_le_card + intro j hj + have hbad := (Finset.mem_filter.mp hj).2 + apply Finset.mem_filter.mpr + refine ⟨Finset.mem_univ j, ?_⟩ + have hnot : maskedFullRank (L.get j).2 d ≠ true := by + intro hgood + exact hbad (noDropTranscripts_of_maskedFullRank e he (L.get j) + (hL.2.1 _ (List.get_mem _ _)) (y j) π Z hgood) + simpa using hnot + +end Klr.StageRank diff --git a/LeanPool/KLRandomness/StageRankAverage.lean b/LeanPool/KLRandomness/StageRankAverage.lean new file mode 100644 index 0000000000..61b993290c --- /dev/null +++ b/LeanPool/KLRandomness/StageRankAverage.lean @@ -0,0 +1,148 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.StageRank +import Mathlib.Tactic.Linarith +import Mathlib.Tactic.Ring + +/-! +# Averaging the actual rank-drop events over the candidate list + +The finite verifier controls the number of failing candidates separately on +each answer sequence with a dense never-read mask. Integrating that count +gives an average of the actual Borel rank-drop probabilities. This order of +quantifiers permits later simultaneous selection for several scans. +-/ + +@[expose] public section + +noncomputable section + +namespace Klr.StageRank + +open MeasureTheory SparseListSearch SparseListWeights SparseSearch SparseListCode PoolQuery +open scoped BigOperators + +/-- The exact missed count is a measurable real-valued function. -/ +theorem measurable_missedCount_real (π : ScanRule) (G : Finset ℕ) : + Measurable (fun Z => (missedCount π G Z : ℝ)) := by + have he : (fun Z => (missedCount π G Z : ℝ)) = + fun Z => (G.card : ℝ) - ∑ a ∈ G, indicator π a Z := by + funext Z + have h := sum_indicator_add_missedCount π G Z + linarith + rw [he] + exact measurable_const.sub (Finset.measurable_sum G fun a _ => measurable_indicator π a) + +open Classical in +/-- A pointwise count bound outside one exceptional event integrates to a +bound for the sum of the actual event probabilities. -/ +theorem sum_measureReal_le_of_card {Ω ι : Type*} [MeasurableSpace Ω] [Fintype ι] + (μ : Measure Ω) [IsProbabilityMeasure μ] (A : ι → Set Ω) + (hA : ∀ i, MeasurableSet (A i)) (E : Set Ω) (hE : MeasurableSet E) + (C : ℝ) (hC : 0 ≤ C) + (hcount : ∀ x ∉ E, + ((Finset.univ.filter fun i => x ∈ A i).card : ℝ) ≤ C) : + (∑ i, μ.real (A i)) ≤ (Fintype.card ι : ℝ) * μ.real E + C := by + classical + let f (i : ι) := (A i).indicator (fun _ => (1 : ℝ)) + have hf : ∀ i, Integrable (f i) μ := fun i => (integrable_const 1).indicator (hA i) + have hg : Integrable (fun x => E.indicator (fun _ => (Fintype.card ι : ℝ)) x + C) μ := + ((integrable_const _).indicator hE).add (integrable_const _) + have hpoint : ∀ x, (∑ i, f i x) ≤ + E.indicator (fun _ => (Fintype.card ι : ℝ)) x + C := by + intro x + have hsum : (∑ i, f i x) = + ((Finset.univ.filter fun i => x ∈ A i).card : ℝ) := by + simp [f, Set.indicator_apply] + rw [hsum] + by_cases hx : x ∈ E + · rw [Set.indicator_of_mem hx] + apply le_trans _ (le_add_of_nonneg_right hC) + exact_mod_cast (Finset.card_filter_le (s := Finset.univ) (fun i => x ∈ A i)) + · simpa only [Set.indicator_of_notMem hx, zero_add] using hcount x hx + calc + (∑ i, μ.real (A i)) = ∫ x, ∑ i, f i x ∂μ := by + rw [integral_finsetSum Finset.univ (fun i _ => hf i)] + simp [f, integral_indicator_const, hA] + _ ≤ ∫ x, E.indicator (fun _ => (Fintype.card ι : ℝ)) x + C ∂μ := + integral_mono (integrable_finsetSum _ (fun i _ => hf i)) hg hpoint + _ = (Fintype.card ι : ℝ) * μ.real E + C := by + rw [integral_add ((integrable_const _).indicator hE) (integrable_const _)] + simp [hE, mul_comm] + +/-- The low-part average rank-drop probability of the actual checked list +is at most the low pool exception plus the verifier's bad-rank fraction. -/ +theorem average_measureReal_low_hasDrop_le + {M m r J : ℕ} {τ θ : ℚ} {L : CodeList} + (hL : Good M m r J τ θ L) (hJ : 0 < J) (hθ : 0 ≤ θ) + (e : Fin M → ℕ) (he : Function.Injective e) + (y : Fin L.length → Fin r → ZMod 2) + (π : ScanRule) (Low : Set Cantor) (hLow : MeasurableSet Low) + (η : ℝ) + (hpool : fairCoin.real {Z | Z ∈ Low ∧ + (missedCount π (Finset.univ.image e) Z : ℝ) < (τ : ℝ) * M} ≤ η) : + (∑ j : Fin L.length, fairCoin.real + (Low ∩ (NoDrop.noDropTranscripts (listBlock hL e he y j) π)ᶜ)) / J ≤ + η + (θ : ℝ) := by + classical + let A (j : Fin L.length) := + Low ∩ (NoDrop.noDropTranscripts (listBlock hL e he y j) π)ᶜ + let E := {Z | Z ∈ Low ∧ + (missedCount π (Finset.univ.image e) Z : ℝ) < (τ : ℝ) * M} + have hA : ∀ j, MeasurableSet (A j) := fun j => + hLow.inter (NoDrop.measurableSet_noDropTranscripts _ _).compl + have hE : MeasurableSet E := + hLow.inter (measurableSet_lt (measurable_missedCount_real π _) measurable_const) + have hcount : ∀ Z ∉ E, + ((Finset.univ.filter fun j => Z ∈ A j).card : ℝ) ≤ (θ : ℝ) * J := by + intro Z hZE + by_cases hZL : Z ∈ Low + · have hden : (τ : ℝ) * M ≤ (missedCount π (Finset.univ.image e) Z : ℝ) := + not_lt.mp (fun h => hZE ⟨hZL, h⟩) + have hden' : τ * (M : ℚ) ≤ ((neverRead e π Z).card : ℚ) := by + rw [card_neverRead e he π Z] + exact_mod_cast hden + have hbad : + ((Finset.univ.filter fun j : Fin L.length => + Z ∉ NoDrop.noDropTranscripts (listBlock hL e he y j) π).card : ℝ) ≤ + (θ : ℝ) * J := by + exact_mod_cast card_hasDrop_le hL e he y π Z hden' + apply le_trans _ hbad + exact_mod_cast (Finset.card_le_card (show + (Finset.univ.filter fun j => Z ∈ A j) ⊆ + (Finset.univ.filter fun j : Fin L.length => + Z ∉ NoDrop.noDropTranscripts (listBlock hL e he y j) π) from by + intro j hj + exact Finset.mem_filter.mpr ⟨Finset.mem_univ _, (Finset.mem_filter.mp hj).2.2⟩)) + · have hzero : (Finset.univ.filter fun j => Z ∈ A j) = ∅ := by + apply Finset.filter_eq_empty_iff.mpr + intro j _ hj + exact hZL hj.1 + rw [hzero, Finset.card_empty, Nat.cast_zero] + exact mul_nonneg (by exact_mod_cast hθ) (Nat.cast_nonneg _) + have hsum := sum_measureReal_le_of_card fairCoin A hA E hE ((θ : ℝ) * J) + (mul_nonneg (by exact_mod_cast hθ) (Nat.cast_nonneg _)) (fun Z hZE => by + convert hcount Z hZE using 1 + congr 2 + ext j + simp) + have hsum' : (∑ j, fairCoin.real (A j)) ≤ (J : ℝ) * η + (θ : ℝ) * J := by + calc + _ ≤ (J : ℝ) * fairCoin.real E + (θ : ℝ) * J := by + simpa only [Fintype.card_fin, hL.1] using hsum + _ ≤ _ := by + exact add_le_add (mul_le_mul_of_nonneg_left hpool (Nat.cast_nonneg J)) le_rfl + apply (div_le_iff₀ (by exact_mod_cast hJ : (0 : ℝ) < J)).mpr + calc + _ ≤ (J : ℝ) * η + (θ : ℝ) * J := hsum' + _ = (η + (θ : ℝ)) * J := by ring + +end Klr.StageRank diff --git a/LeanPool/KLRandomness/StageRankCode.lean b/LeanPool/KLRandomness/StageRankCode.lean new file mode 100644 index 0000000000..186dd22823 --- /dev/null +++ b/LeanPool/KLRandomness/StageRankCode.lean @@ -0,0 +1,198 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.StageRankZero +public import LeanPool.KLRandomness.PoolAdviceComputable + +/-! +# Executable unread masks and finite rank predicates + +All queries used here are made on a finite prescribed answer transcript. +The unread mask is a total finite computation from the concrete pool list, +and the full-rank and zero-rank tests agree with the mathematical affine +block on that list. No limiting query information is used by these tests. +-/ + +@[expose] public section + +namespace Klr.StageRankCode + +open SparseSearch SparseListSearch SparseListCode AffineCode EffectiveScan FiniteMeasure + +/-- The concrete Boolean unread-pool mask after the supplied finite transcript. -/ +def unreadMask (π : ScanRule) (G : List ℕ) (v : List Bool) : List Bool := + tabulate (fun j => !PoolAdvice.readsBefore [π] 0 (G.getD j 0) v.length v) G.length + +@[simp] theorem length_unreadMask (π : ScanRule) (G : List ℕ) (v : List Bool) : + (unreadMask π G v).length = G.length := by simp [unreadMask, tabulate] + +theorem computable_unreadMask (π : ScanRule) : + Computable (fun p : List ℕ × List Bool => unreadMask π p.1 p.2) := by + have hG : Computable (fun p : (List ℕ × List Bool) × ℕ => p.1.1) := + Computable.fst.comp Computable.fst + have hv : Computable (fun p : (List ℕ × List Bool) × ℕ => p.1.2) := + Computable.snd.comp Computable.fst + have ha := (Primrec.list_getD (0 : ℕ)).to_comp.comp hG Computable.snd + have hread := PoolAdvice.computable_readsBefore [π] (Computable.const 0) ha + (Computable.list_length.comp hv) hv + have hbit := Primrec.not.to_comp.comp hread + have htab := (computable_tabulate (f := fun p : List ℕ × List Bool => fun j => + !PoolAdvice.readsBefore [π] 0 (p.1.getD j 0) p.2.length p.2) hbit.to₂).comp + (Computable.id.pair (Computable.list_length.comp Computable.fst)) + exact htab + +theorem readsBefore_iff_mem_queriedPositions (π : ScanRule) (a : ℕ) (v : List Bool) : + PoolAdvice.readsBefore [π] 0 a v.length v = true ↔ a ∈ π.queriedPositions v := by + rw [PoolAdvice.readsBefore_eq_true] + constructor + · rintro ⟨t, ht, hq⟩ + exact Finset.mem_image.mpr ⟨⟨t, ht⟩, Finset.mem_univ _, hq⟩ + · intro h + obtain ⟨t, _, ht⟩ := Finset.mem_image.mp h + exact ⟨t.val, t.isLt, ht⟩ + +/-- The executable mask equals the exact finite unread-pool mask. -/ +theorem unreadMask_eq_mask (π : ScanRule) (G : List ℕ) (v : List Bool) : + unreadMask π G v = mask (StageRank.unreadPool G.get π v) := by + apply List.ext_getElem (by simp) + intro j hj hk + have hjG : j < G.length := by simpa using hj + rw [← List.getD_eq_getElem _ false hj, ← List.getD_eq_getElem _ false hk] + rw [unreadMask, getD_tabulate _ hjG] + rw [getD_mask _ (⟨j, hjG⟩ : Fin G.length)] + apply Bool.eq_iff_iff.mpr + rw [Bool.not_eq_true_eq_eq_false, Bool.eq_false_iff, decide_eq_true_eq, + StageRank.mem_unreadPool] + have hget : G.getD j 0 = G.get ⟨j, hjG⟩ := List.getD_eq_getElem _ _ hjG + rw [hget] + exact not_congr (readsBefore_iff_mem_queriedPositions π (G.get ⟨j, hjG⟩) v) + +/-- A finite Boolean zero test for every entry of the coded rectangle. -/ +def zeroMatrix (c : Data) : Bool := + boundedAll (fun i => boundedAll (fun j => !entry (rows c) i j) (width c)) (rank c) + +theorem computable_zeroMatrix : Computable zeroMatrix := by + have hc : Computable (fun p : (Data × ℕ) × ℕ => p.1.1) := + Computable.fst.comp Computable.fst + have hi : Computable (fun p : (Data × ℕ) × ℕ => p.1.2) := + Computable.snd.comp Computable.fst + have he := computable_entry.comp ((computable_rows.comp hc).pair (hi.pair Computable.snd)) + have hb := (computable_boundedAll + (p := fun p : Data × ℕ => fun j => !entry (rows p.1) p.2 j) + (Primrec.not.to_comp.comp he).to₂).comp + (Computable.id.pair (computable_width.comp Computable.fst)) + have hall := (computable_boundedAll + (p := fun c : Data => fun i => boundedAll (fun j => !entry (rows c) i j) (width c)) + hb.to₂).comp (Computable.id.pair computable_rank) + exact hall + +theorem zeroMatrix_eq_true (c : Data) : zeroMatrix c = true ↔ matrix c = 0 := by + rw [zeroMatrix, boundedAll_eq_true] + constructor + · intro h + ext i j + have hz := (boundedAll_eq_true _ _).mp (h i.val i.isLt) j.val j.isLt + have he : entry (rows c) i.val j.val = false := by simpa using hz + change boolEquivF2 (entry (rows c) i.val j.val) = (0 : ZMod 2) + rw [he] + rfl + · intro h i hi + rw [boundedAll_eq_true] + intro j hj + have hz := congrFun (congrFun h (⟨i, hi⟩ : Fin (rank c))) (⟨j, hj⟩ : Fin (width c)) + have he : entry (rows c) i j = false := boolEquivF2.injective hz + simp only [he, Bool.not_false] + +/-- Check whether full unread row rank remains. -/ +def fullRankTest (π : ScanRule) (G : List ℕ) (c : Data) (v : List Bool) : Bool := + maskedFullRank c (unreadMask π G v) + +/-- Check whether unread row rank is zero. -/ +def zeroRankTest (π : ScanRule) (G : List ℕ) (c : Data) (v : List Bool) : Bool := + zeroMatrix (maskCode c (unreadMask π G v)) + +theorem computable_fullRankTest (π : ScanRule) {α : Type*} [Primcodable α] + {G : α → List ℕ} {c : α → Data} {v : α → List Bool} + (hG : Computable G) (hc : Computable c) (hv : Computable v) : + Computable (fun p => fullRankTest π (G p) (c p) (v p)) := + computable_maskedFullRank.comp hc ((computable_unreadMask π).comp (hG.pair hv)) + +theorem computable_zeroRankTest (π : ScanRule) {α : Type*} [Primcodable α] + {G : α → List ℕ} {c : α → Data} {v : α → List Bool} + (hG : Computable G) (hc : Computable c) (hv : Computable v) : + Computable (fun p => zeroRankTest π (G p) (c p) (v p)) := + computable_zeroMatrix.comp + (computable_maskCode.comp hc ((computable_unreadMask π).comp (hG.pair hv))) + +theorem fullRankTest_eq_true (π : ScanRule) (G : List ℕ) (hG : G.Nodup) + {m r : ℕ} (a : Entry) (ha : GoodEntry G.length m r a) + (y : Fin r → ZMod 2) (v : List Bool) : + fullRankTest π G a.2 v = true ↔ + (StageCandidate.block G.get hG.injective_get a ha y).UnreadFullRank π v := by + rw [fullRankTest, unreadMask_eq_mask] + exact (StageRank.unreadFullRank_iff_maskedFullRank _ _ _ _ _ _ _).symm + +theorem zeroRankTest_eq_true (π : ScanRule) (G : List ℕ) (hG : G.Nodup) + {m r : ℕ} (a : Entry) (ha : GoodEntry G.length m r a) + (y : Fin r → ZMod 2) (v : List Bool) : + zeroRankTest π G a.2 v = true ↔ + (StageCandidate.block G.get hG.injective_get a ha y).remainingRank π v = 0 := by + rw [zeroRankTest, zeroMatrix_eq_true, unreadMask_eq_mask] + exact (StageRank.remainingRank_eq_zero_iff_masked_matrix_eq_zero _ _ _ _ _ _ _).symm + +/-- A rank drop has already occurred precisely when full unread rank is lost. -/ +def dropTest (π : ScanRule) (G : List ℕ) (c : Data) (v : List Bool) : Bool := + !fullRankTest π G c v + +/-- Strictly partial unread rank is positive and below full rank. -/ +def partialTest (π : ScanRule) (G : List ℕ) (c : Data) (v : List Bool) : Bool := + !zeroRankTest π G c v && !fullRankTest π G c v + +theorem computable_dropTest (π : ScanRule) {α : Type*} [Primcodable α] + {G : α → List ℕ} {c : α → Data} {v : α → List Bool} + (hG : Computable G) (hc : Computable c) (hv : Computable v) : + Computable (fun p => dropTest π (G p) (c p) (v p)) := + Primrec.not.to_comp.comp (computable_fullRankTest π hG hc hv) + +theorem computable_partialTest (π : ScanRule) {α : Type*} [Primcodable α] + {G : α → List ℕ} {c : α → Data} {v : α → List Bool} + (hG : Computable G) (hc : Computable c) (hv : Computable v) : + Computable (fun p => partialTest π (G p) (c p) (v p)) := + Primrec.and.to_comp.comp + (Primrec.not.to_comp.comp (computable_zeroRankTest π hG hc hv)) + (Primrec.not.to_comp.comp (computable_fullRankTest π hG hc hv)) + +theorem dropTest_eq_true (π : ScanRule) (G : List ℕ) (hG : G.Nodup) + {m r : ℕ} (a : Entry) (ha : GoodEntry G.length m r a) + (y : Fin r → ZMod 2) (v : List Bool) : + dropTest π G a.2 v = true ↔ + (StageCandidate.block G.get hG.injective_get a ha y).remainingRank π v < r := by + rw [dropTest, Bool.not_eq_true_eq_eq_false, Bool.eq_false_iff] + let B := StageCandidate.block G.get hG.injective_get a ha y + have h := (fullRankTest_eq_true π G hG a ha y v).trans + (B.unreadFullRank_iff_remainingRank π v) + apply (not_congr h).trans + have hle : B.remainingRank π v ≤ r := B.remainingRank_le π v + change (¬B.remainingRank π v = r) ↔ B.remainingRank π v < r + omega + +theorem partialTest_eq_true (π : ScanRule) (G : List ℕ) (hG : G.Nodup) + {m r : ℕ} (a : Entry) (ha : GoodEntry G.length m r a) + (y : Fin r → ZMod 2) (v : List Bool) : + partialTest π G a.2 v = true ↔ + 0 < (StageCandidate.block G.get hG.injective_get a ha y).remainingRank π v ∧ + (StageCandidate.block G.get hG.injective_get a ha y).remainingRank π v < r := by + change (!zeroRankTest π G a.2 v && dropTest π G a.2 v) = true ↔ _ + rw [Bool.and_eq_true, dropTest_eq_true π G hG a ha y v, + Bool.not_eq_true_eq_eq_false, Bool.eq_false_iff] + apply and_congr _ Iff.rfl + exact (not_congr (zeroRankTest_eq_true π G hG a ha y v)).trans Nat.pos_iff_ne_zero.symm + +end Klr.StageRankCode diff --git a/LeanPool/KLRandomness/StageRankLimit.lean b/LeanPool/KLRandomness/StageRankLimit.lean new file mode 100644 index 0000000000..9707bcc12b --- /dev/null +++ b/LeanPool/KLRandomness/StageRankLimit.lean @@ -0,0 +1,195 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.LateDropBound +public import LeanPool.KLRandomness.PoolCoverage +public import Mathlib.Order.OrderIsoNat + +/-! +# The eventual rank events of an actual affine block + +Remaining rank is a nonincreasing natural number along every input, hence +stabilizes. The limiting partial-rank event is measurable and is contained +in the event of a rank drop and in the event that some support coordinate +is never queried. Splitting these two inclusions along an arbitrary answer +partition gives the stage construction's high-miss / low-drop bound. + +All rank events below are events in input space. The pool missed count and +the partition are evaluated on the scan's actual infinite observation map. +-/ + +@[expose] public section + +namespace Klr.StageRankLimit + +open MeasureTheory Filter PoolQuery +open scoped Topology + +/-- Remaining rank stabilizes on every input. No uniform stopping time or +computable modulus is asserted. -/ +theorem remainingRank_stabilizes (B : AffineBlock) (π : ScanRule) (X : Cantor) : + ∃ N, ∀ n, N ≤ n → + B.remainingRank π (π.transcript X n) = B.remainingRank π (π.transcript X N) := by + obtain ⟨N, hN⟩ := WellFoundedLT.antitone_chain_condition + (B.remainingRank_transcript_antitone π X) + exact ⟨N, fun n hn => (hN n hn).symm⟩ + +/-- Inputs whose eventual remaining rank is positive but below the initial rank. -/ +def eventualPartialEvent (B : AffineBlock) (π : ScanRule) : Set Cantor := + {X | ∀ᶠ n in atTop, X ∈ LateDropBound.partialEvent B π n} + +theorem measurableSet_eventualPartialEvent (B : AffineBlock) (π : ScanRule) : + MeasurableSet (eventualPartialEvent B π) := by + have he : eventualPartialEvent B π = + ⋃ N : ℕ, ⋂ n : {n : ℕ // N ≤ n}, LateDropBound.partialEvent B π n.val := by + ext X + simp only [eventualPartialEvent, Set.mem_ofPred_eq, eventually_atTop, + Set.mem_iUnion, Set.mem_iInter] + exact ⟨fun ⟨N, hN⟩ => ⟨N, fun n => hN n.val n.property⟩, + fun ⟨N, hN⟩ => ⟨N, fun n hn => hN ⟨n, hn⟩⟩⟩ + rw [he] + exact MeasurableSet.iUnion fun N => MeasurableSet.iInter fun n => + LateDropBound.measurableSet_partialEvent B π n.val + +/-- Membership in finite partial-rank events eventually agrees with the +limiting event on each individual input. -/ +theorem eventually_partialEvent_iff (B : AffineBlock) (π : ScanRule) (X : Cantor) : + ∀ᶠ n in atTop, + X ∈ LateDropBound.partialEvent B π n ↔ X ∈ eventualPartialEvent B π := by + obtain ⟨N, hN⟩ := remainingRank_stabilizes B π X + have hsame (n : ℕ) (hn : N ≤ n) : + X ∈ LateDropBound.partialEvent B π n ↔ X ∈ LateDropBound.partialEvent B π N := by + simp only [LateDropBound.partialEvent, Set.mem_ofPred_eq, hN n hn] + have hlim : X ∈ eventualPartialEvent B π ↔ X ∈ LateDropBound.partialEvent B π N := by + constructor + · intro h + obtain ⟨n, hn, hp⟩ := ((eventually_ge_atTop N).and h).exists + exact (hsame n hn).mp hp + · intro h + exact (eventually_ge_atTop N).mono fun n hn => (hsame n hn).mpr h + exact (eventually_ge_atTop N).mono fun n hn => (hsame n hn).trans hlim.symm + +/-- Having read every support coordinate forces the remaining rank to zero. -/ +theorem remainingRank_eq_zero_of_all_observed (B : AffineBlock) (π : ScanRule) + (v : List Bool) (hobs : ∀ p : B.support, p ∈ B.observed π v) : + B.remainingRank π v = 0 := by + classical + let : IsEmpty {p : B.support // p ∉ B.observed π v} := + ⟨fun p => p.property (hobs p.val)⟩ + have hmap : AffineObservation.unreadMap B.matrix (B.observed π v) = 0 := by + apply LinearMap.ext + intro u + rw [Subsingleton.elim u 0, map_zero, LinearMap.zero_apply] + simp [AffineBlock.remainingRank, hmap] + +/-- If every support coordinate is eventually read, a finite input-dependent +horizon has zero remaining rank, and it stays zero thereafter. -/ +theorem eventually_remainingRank_zero_of_reads (B : AffineBlock) (π : ScanRule) + (X : Cantor) (hall : ∀ a ∈ B.support, Reads π a (π.observationMap X)) : + ∀ᶠ n in atTop, B.remainingRank π (π.transcript X n) = 0 := by + classical + choose t ht using (fun p : B.support => hall p.val p.property) + let N := Finset.univ.sup fun p : B.support => t p + 1 + have hobs : ∀ p : B.support, p ∈ B.observed π (π.transcript X N) := by + intro p + have htN : t p < N := lt_of_lt_of_le (Nat.lt_succ_self _) + (Finset.le_sup (f := fun p : B.support => t p + 1) (Finset.mem_univ p)) + change p.val ∈ π.queriedPositions (π.transcript X N) + unfold ScanRule.queriedPositions + apply Finset.mem_image.mpr + refine ⟨⟨t p, by simpa using htN⟩, Finset.mem_univ _, ?_⟩ + simpa only [PoolQuery.queryAt, π.inputPrefix_observationMap, + π.transcript_take X htN.le] using ht p + have hzero := remainingRank_eq_zero_of_all_observed B π (π.transcript X N) hobs + filter_upwards [eventually_ge_atTop N] with n hn + have hle := B.remainingRank_transcript_antitone π X hn + exact Nat.eq_zero_of_le_zero (hzero ▸ hle) + +/-- Positive limiting rank requires that some coordinate of any containing +pool is never queried. The pool event is pulled back from answer space. -/ +theorem eventualPartialEvent_subset_missed (B : AffineBlock) (π : ScanRule) + (G : Finset ℕ) (hBG : B.support ⊆ G) : + eventualPartialEvent B π ⊆ + {X | 0 < missedCount π G (π.observationMap X)} := by + intro X hX + by_contra hmiss + have hall := (missedCount_eq_zero_iff π G (π.observationMap X)).mp + (Nat.eq_zero_of_not_pos hmiss) + have hz := eventually_remainingRank_zero_of_reads B π X (fun a ha => hall a (hBG ha)) + obtain ⟨n, hpartial, hzero⟩ := (hX.and hz).exists + exact (Nat.ne_of_gt hpartial.1) hzero + +/-- Loss of full rank by a fixed finite horizon; this is the event `T ≤ n` +for the one-based first-drop query number. -/ +def droppedBy (B : AffineBlock) (π : ScanRule) (n : ℕ) : Set Cantor := + (NoDrop.survivalEvent B π n)ᶜ + +theorem measurableSet_droppedBy (B : AffineBlock) (π : ScanRule) (n : ℕ) : + MeasurableSet (droppedBy B π n) := + (NoDrop.measurableSet_survivalEvent B π n).compl + +theorem droppedBy_mono (B : AffineBlock) (π : ScanRule) : Monotone (droppedBy B π) := + fun _ _ h => Set.compl_subset_compl.mpr (NoDrop.survivalEvent_antitone B π h) + +theorem mem_droppedBy_iff (B : AffineBlock) (π : ScanRule) (n : ℕ) (X : Cantor) : + X ∈ droppedBy B π n ↔ B.remainingRank π (π.transcript X n) < B.rank := by + change ¬B.UnreadFullRank π (π.transcript X n) ↔ _ + rw [B.unreadFullRank_iff_remainingRank] + have hle := B.remainingRank_le π (π.transcript X n) + omega + +theorem iUnion_droppedBy (B : AffineBlock) (π : ScanRule) : + (⋃ n, droppedBy B π n) = LateDropBound.hasDrop B π := by + ext X + simp only [droppedBy, Set.mem_iUnion, Set.mem_compl_iff, NoDrop.survivalEvent, + Set.mem_ofPred_eq, LateDropBound.hasDrop, NoDrop.noDropEvent, not_forall] + +theorem droppedBy_subset_hasDrop (B : AffineBlock) (π : ScanRule) (n : ℕ) : + droppedBy B π n ⊆ LateDropBound.hasDrop B π := by + rw [← iUnion_droppedBy] + exact Set.subset_iUnion _ n + +/-- The first-drop tail is exactly the part of the eventual-drop event not +yet seen by the horizon. This retains the paper's one-based query indexing. -/ +theorem rankDropTailEvent_eq_sdiff (B : AffineBlock) (π : ScanRule) (N : ℕ) : + StoppingTranscript.rankDropTailEvent B π N = + LateDropBound.hasDrop B π \ droppedBy B π N := by + classical + ext X + constructor + · rintro ⟨n, hN, hfull, hfail⟩ + refine ⟨fun hno => hfail (hno (n + 1)), ?_⟩ + simpa only [droppedBy, Set.mem_compl_iff, not_not, NoDrop.survivalEvent, + Set.mem_ofPred_eq] using hfull N hN + · rintro ⟨hdrop, hfull⟩ + apply LateDropBound.mem_rankDropTail_of_full_and_hasDrop B π N X _ hdrop + simpa only [droppedBy, Set.mem_compl_iff, not_not, NoDrop.survivalEvent, + Set.mem_ofPred_eq] using hfull + +theorem eventualPartialEvent_subset_hasDrop (B : AffineBlock) (π : ScanRule) : + eventualPartialEvent B π ⊆ LateDropBound.hasDrop B π := by + intro X hX + obtain ⟨n, hn⟩ := hX.exists + exact droppedBy_subset_hasDrop B π n ((mem_droppedBy_iff B π n X).mpr hn.2) + +/-- The limiting partial-rank event is covered by the high-part pool-miss +event and the low-part rank-drop event used in the simultaneous score. -/ +theorem eventualPartialEvent_subset_highMiss_union_lowDrop + (B : AffineBlock) (π : ScanRule) (G : Finset ℕ) (hBG : B.support ⊆ G) + (H : Set Cantor) : + eventualPartialEvent B π ⊆ + (π.observationMap ⁻¹' H ∩ {X | 0 < missedCount π G (π.observationMap X)}) ∪ + (π.observationMap ⁻¹' Hᶜ ∩ LateDropBound.hasDrop B π) := by + intro X hX + by_cases hH : π.observationMap X ∈ H + · exact Or.inl ⟨hH, eventualPartialEvent_subset_missed B π G hBG hX⟩ + · exact Or.inr ⟨hH, eventualPartialEvent_subset_hasDrop B π hX⟩ + +end Klr.StageRankLimit diff --git a/LeanPool/KLRandomness/StageRankLimitMeasure.lean b/LeanPool/KLRandomness/StageRankLimitMeasure.lean new file mode 100644 index 0000000000..3fa6bb4466 --- /dev/null +++ b/LeanPool/KLRandomness/StageRankLimitMeasure.lean @@ -0,0 +1,206 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.StageRankLimit +public import LeanPool.KLRandomness.StageHorizonComputable +public import Mathlib.MeasureTheory.Integral.DominatedConvergence +import Mathlib.Tactic.Linarith + +/-! +# Limits of the actual finite-horizon rank probabilities + +For any finite input measure, bounded convergence turns pointwise rank +stabilization into convergence of the partial-rank probabilities. Continuity +from below gives convergence of the probabilities of a drop by time `n`. +Finite sums supply exactly the two limits used by the bounded-advice horizon +search. The first-drop tail is the difference between the limiting drop mass +and the mass already seen. +-/ + +@[expose] public section + +noncomputable section + +namespace Klr.StageRankLimit + +open MeasureTheory Filter PoolQuery +open scoped Topology BigOperators + +/-- Bounded convergence for the actual finite partial-rank events. -/ +theorem tendsto_partial_probability (μ : Measure Cantor) [IsFiniteMeasure μ] + (B : AffineBlock) (π : ScanRule) : + Tendsto (fun n => μ.real (LateDropBound.partialEvent B π n)) atTop + (𝓝 (μ.real (eventualPartialEvent B π))) := by + classical + have h := tendsto_integral_of_dominated_convergence (μ := μ) + (F := fun n => (LateDropBound.partialEvent B π n).indicator (fun _ => (1 : ℝ))) + (f := (eventualPartialEvent B π).indicator (fun _ => (1 : ℝ))) + (fun _ => (1 : ℝ)) + (fun n => (measurable_const.indicator + (LateDropBound.measurableSet_partialEvent B π n)).aestronglyMeasurable) + (integrable_const 1) (fun n => Eventually.of_forall fun X => by + by_cases hX : X ∈ LateDropBound.partialEvent B π n <;> + simp [hX]) + (Eventually.of_forall fun X => by + apply tendsto_const_nhds.congr' + filter_upwards [eventually_partialEvent_iff B π X] with n hn + simp only [Set.indicator_apply, hn]) + have hfinite (n : ℕ) : + (∫ X, (LateDropBound.partialEvent B π n).indicator (fun _ => (1 : ℝ)) X ∂μ) = + μ.real (LateDropBound.partialEvent B π n) := + integral_indicator_one (LateDropBound.measurableSet_partialEvent B π n) + have hlimit : + (∫ X, (eventualPartialEvent B π).indicator (fun _ => (1 : ℝ)) X ∂μ) = + μ.real (eventualPartialEvent B π) := + integral_indicator_one (measurableSet_eventualPartialEvent B π) + simpa only [hfinite, hlimit] using h + +/-- The drop-by-time probabilities increase to the probability of any drop. -/ +theorem tendsto_drop_probability (μ : Measure Cantor) [IsFiniteMeasure μ] + (B : AffineBlock) (π : ScanRule) : + Tendsto (fun n => μ.real (droppedBy B π n)) atTop + (𝓝 (μ.real (LateDropBound.hasDrop B π))) := by + have h := tendsto_measure_iUnion_atTop (μ := μ) (droppedBy_mono B π) + rw [iUnion_droppedBy] at h + exact (ENNReal.tendsto_toReal (measure_ne_top μ _)).comp h + +/-- The exact finite-stage first-drop tail identity. -/ +theorem tail_probability_eq_sub (μ : Measure Cantor) [IsFiniteMeasure μ] + (B : AffineBlock) (π : ScanRule) (N : ℕ) : + μ.real (StoppingTranscript.rankDropTailEvent B π N) = + μ.real (LateDropBound.hasDrop B π) - μ.real (droppedBy B π N) := by + rw [rankDropTailEvent_eq_sdiff, + measureReal_sdiff (droppedBy_subset_hasDrop B π N) (measurableSet_droppedBy B π N)] + +/-- The limiting partial-rank probability is controlled by the two actual +input-space events used to select the candidate. -/ +theorem partial_limit_probability_le (μ : Measure Cantor) [IsFiniteMeasure μ] + (B : AffineBlock) (π : ScanRule) (G : Finset ℕ) (hBG : B.support ⊆ G) + (H : Set Cantor) : + μ.real (eventualPartialEvent B π) ≤ + μ.real (π.observationMap ⁻¹' H ∩ + {X | 0 < missedCount π G (π.observationMap X)}) + + μ.real (π.observationMap ⁻¹' Hᶜ ∩ LateDropBound.hasDrop B π) := + (measureReal_mono + (eventualPartialEvent_subset_highMiss_union_lowDrop B π G hBG H)).trans + (measureReal_union_le _ _) + +variable {ι : Type*} [Fintype ι] + +/-- Sum of finite partial-rank probabilities for the protected scan family. -/ +def partialMass (μ : Measure Cantor) (B : AffineBlock) (π : ι → ScanRule) (n : ℕ) : ℝ := + ∑ i, μ.real (LateDropBound.partialEvent B (π i) n) + +/-- Sum of limiting partial-rank probabilities. -/ +def partialLimitMass (μ : Measure Cantor) (B : AffineBlock) (π : ι → ScanRule) : ℝ := + ∑ i, μ.real (eventualPartialEvent B (π i)) + +/-- Sum of probabilities of a first drop by the horizon. -/ +def dropMass (μ : Measure Cantor) (B : AffineBlock) (π : ι → ScanRule) (n : ℕ) : ℝ := + ∑ i, μ.real (droppedBy B (π i) n) + +/-- Sum of probabilities that a first drop ever occurs. -/ +def dropLimitMass (μ : Measure Cantor) (B : AffineBlock) (π : ι → ScanRule) : ℝ := + ∑ i, μ.real (LateDropBound.hasDrop B (π i)) + +theorem tendsto_partialMass (μ : Measure Cantor) [IsFiniteMeasure μ] + (B : AffineBlock) (π : ι → ScanRule) : + Tendsto (partialMass μ B π) atTop (𝓝 (partialLimitMass μ B π)) := + tendsto_finsetSum _ fun i _ => tendsto_partial_probability μ B (π i) + +theorem tendsto_dropMass (μ : Measure Cantor) [IsFiniteMeasure μ] + (B : AffineBlock) (π : ι → ScanRule) : + Tendsto (dropMass μ B π) atTop (𝓝 (dropLimitMass μ B π)) := + tendsto_finsetSum _ fun i _ => tendsto_drop_probability μ B (π i) + +theorem dropMass_mono (μ : Measure Cantor) [IsFiniteMeasure μ] + (B : AffineBlock) (π : ι → ScanRule) : Monotone (dropMass μ B π) := by + intro m n hmn + exact Finset.sum_le_sum fun i _ => measureReal_mono (droppedBy_mono B (π i) hmn) + +theorem dropLimitMass_nonneg (μ : Measure Cantor) (B : AffineBlock) + (π : ι → ScanRule) : 0 ≤ dropLimitMass μ B π := + Finset.sum_nonneg fun _ _ => measureReal_nonneg + +/-- The total first-drop mass is at most the number of protected strategies. -/ +theorem dropLimitMass_le_card (μ : Measure Cantor) [IsProbabilityMeasure μ] + (B : AffineBlock) (π : ι → ScanRule) : + dropLimitMass μ B π ≤ Fintype.card ι := by + calc + _ ≤ ∑ _i : ι, (1 : ℝ) := Finset.sum_le_sum fun _ _ => measureReal_le_one + _ = _ := by simp + +/-- Summing the individual finite-stage tail identities gives the exact +quantity certified by the bounded-advice horizon test. -/ +theorem sum_tail_probability_eq_sub (μ : Measure Cantor) [IsFiniteMeasure μ] + (B : AffineBlock) (π : ι → ScanRule) (N : ℕ) : + (∑ i, μ.real (StoppingTranscript.rankDropTailEvent B (π i) N)) = + dropLimitMass μ B π - dropMass μ B π N := by + simp only [tail_probability_eq_sub, Finset.sum_sub_distrib, dropLimitMass, dropMass] + +/-- The same pool and the same selected block serve every protected scan. -/ +theorem partialLimitMass_le (μ : Measure Cantor) [IsFiniteMeasure μ] + (B : AffineBlock) (π : ι → ScanRule) (G : Finset ℕ) (hBG : B.support ⊆ G) + (H : ι → Set Cantor) : + partialLimitMass μ B π ≤ + (∑ i, μ.real ((π i).observationMap ⁻¹' H i ∩ + {X | 0 < missedCount (π i) G ((π i).observationMap X)})) + + ∑ i, μ.real ((π i).observationMap ⁻¹' (H i)ᶜ ∩ + LateDropBound.hasDrop B (π i)) := by + rw [← Finset.sum_add_distrib] + exact Finset.sum_le_sum fun i _ => partial_limit_probability_le μ B (π i) G hBG (H i) + +/-- The strict simultaneous score bounds yield the partial-rank limit bound +used by the finite horizon search. -/ +theorem partialLimitMass_lt_two_mul (μ : Measure Cantor) [IsFiniteMeasure μ] + (B : AffineBlock) (π : ι → ScanRule) (G : Finset ℕ) (hBG : B.support ⊆ G) + (H : ι → Set Cantor) (error : ℝ) + (hhigh : (∑ i, μ.real ((π i).observationMap ⁻¹' H i ∩ + {X | 0 < missedCount (π i) G ((π i).observationMap X)})) < error) + (hlow : (∑ i, μ.real ((π i).observationMap ⁻¹' (H i)ᶜ ∩ + LateDropBound.hasDrop B (π i))) < error) : + partialLimitMass μ B π < 2 * error := by + have h := partialLimitMass_le μ B π G hBG H + linarith + +/-- Connect exact rational finite-horizon probabilities to the actual +partial-recursive horizon search. Its output bounds the summed first-drop +tails of these scans under this input measure. -/ +theorem exists_bounded_advice_search_of_rank_probabilities + {α : Type*} {error : ℚ} (herror : 0 < error) + {u v : α → ℕ → ℚ} (input : α) + (μ : Measure Cantor) [IsProbabilityMeasure μ] + (B : AffineBlock) (π : ι → ScanRule) (G : Finset ℕ) (hBG : B.support ⊆ G) + (H : ι → Set Cantor) + (hu : ∀ n, (u input n : ℝ) = partialMass μ B π n) + (hv : ∀ n, (v input n : ℝ) = dropMass μ B π n) + (hhigh : (∑ i, μ.real ((π i).observationMap ⁻¹' H i ∩ + {X | 0 < missedCount (π i) G ((π i).observationMap X)})) < (error : ℝ)) + (hlow : (∑ i, μ.real ((π i).observationMap ⁻¹' (H i)ᶜ ∩ + LateDropBound.hasDrop B (π i))) < (error : ℝ)) : + ∃ advice, advice ≤ StageHorizon.adviceBound error (Fintype.card ι) ∧ + (StageHorizon.search error u v (input, advice)).Dom ∧ + ∀ horizon, horizon ∈ StageHorizon.search error u v (input, advice) → + StageHorizon.Accepted error (u input) (v input) advice horizon ∧ + (∑ i, μ.real (StoppingTranscript.rankDropTailEvent B (π i) horizon)) < + 2 * (error : ℝ) := by + have huconv : Tendsto (fun n => (u input n : ℝ)) atTop (𝓝 (partialLimitMass μ B π)) := by + simpa only [hu] using tendsto_partialMass μ B π + have hvconv : Tendsto (fun n => (v input n : ℝ)) atTop (𝓝 (dropLimitMass μ B π)) := by + simpa only [hv] using tendsto_dropMass μ B π + obtain ⟨advice, hadvice, hdom, hspec⟩ := StageHorizon.exists_bounded_advice_search herror input + huconv hvconv (partialLimitMass_lt_two_mul μ B π G hBG H error hhigh hlow).le + (dropLimitMass_nonneg μ B π) (dropLimitMass_le_card μ B π) + refine ⟨advice, hadvice, hdom, fun horizon hhorizon => ?_⟩ + obtain ⟨haccepted, htail⟩ := hspec horizon hhorizon + refine ⟨haccepted, ?_⟩ + rwa [sum_tail_probability_eq_sub, ← hv horizon] + +end Klr.StageRankLimit diff --git a/LeanPool/KLRandomness/StageRankProbability.lean b/LeanPool/KLRandomness/StageRankProbability.lean new file mode 100644 index 0000000000..6d1ede4704 --- /dev/null +++ b/LeanPool/KLRandomness/StageRankProbability.lean @@ -0,0 +1,216 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.StageRankCode +public import LeanPool.KLRandomness.StageFiniteScan +public import LeanPool.KLRandomness.StageRankLimitMeasure + +/-! +# Exact rational partial-rank and rank-drop probabilities + +The finite rank predicates are evaluated on actual adaptive transcripts, +under the finitely conditioned affine law. Summing over a fixed finite list +of scans gives total computable rational sequences whose real values are +exactly the partial-rank and dropped-by-time masses used by the horizon +convergence theorem. +-/ + +@[expose] public section + +namespace Klr.StageRankProbability + +open SparseListSearch StageRankCode RationalComputability +open scoped BigOperators + +/-- Exact finite partial-rank probability for one scan. -/ +def partialProbability (cs : List AffineCode.Data) (π : ScanRule) + (G : List ℕ) (c : AffineCode.Data) (V : ℕ) : ℚ := + StageFiniteScan.probability cs π V (partialTest π G c) + +/-- Exact finite probability that full unread rank has already been lost. -/ +def dropProbability (cs : List AffineCode.Data) (π : ScanRule) + (G : List ℕ) (c : AffineCode.Data) (V : ℕ) : ℚ := + StageFiniteScan.probability cs π V (dropTest π G c) + +theorem computable_partialProbability (π : ScanRule) {α : Type*} [Primcodable α] + {cs : α → List AffineCode.Data} {G : α → List ℕ} + {c : α → AffineCode.Data} {V : α → ℕ} + (hcs : Computable cs) (hG : Computable G) (hc : Computable c) (hV : Computable V) : + Computable (fun p => partialProbability (cs p) π (G p) (c p) (V p)) := + StageFiniteScan.computable_probability π hcs hV + (computable_partialTest π (hG.comp Computable.fst) + (hc.comp Computable.fst) Computable.snd).to₂ + +theorem computable_dropProbability (π : ScanRule) {α : Type*} [Primcodable α] + {cs : α → List AffineCode.Data} {G : α → List ℕ} + {c : α → AffineCode.Data} {V : α → ℕ} + (hcs : Computable cs) (hG : Computable G) (hc : Computable c) (hV : Computable V) : + Computable (fun p => dropProbability (cs p) π (G p) (c p) (V p)) := + StageFiniteScan.computable_probability π hcs hV + (computable_dropTest π (hG.comp Computable.fst) + (hc.comp Computable.fst) Computable.snd).to₂ + +theorem partialProbability_eq_measureReal (cs : List AffineCode.Data) (π : ScanRule) + (G : List ℕ) (hG : G.Nodup) {m r : ℕ} + (a : Entry) (ha : GoodEntry G.length m r a) (y : Fin r → ZMod 2) (V : ℕ) : + (partialProbability cs π G a.2 V : ℝ) = + (StageFiniteProbability.law cs).real (LateDropBound.partialEvent + (StageCandidate.block G.get hG.injective_get a ha y) π V) := by + rw [partialProbability, StageFiniteScan.probability_eq_measureReal] + apply congrArg (StageFiniteProbability.law cs).real + ext X + exact partialTest_eq_true π G hG a ha y (π.transcript X V) + +theorem dropProbability_eq_measureReal (cs : List AffineCode.Data) (π : ScanRule) + (G : List ℕ) (hG : G.Nodup) {m r : ℕ} + (a : Entry) (ha : GoodEntry G.length m r a) (y : Fin r → ZMod 2) (V : ℕ) : + (dropProbability cs π G a.2 V : ℝ) = + (StageFiniteProbability.law cs).real (StageRankLimit.droppedBy + (StageCandidate.block G.get hG.injective_get a ha y) π V) := by + rw [dropProbability, StageFiniteScan.probability_eq_measureReal] + apply congrArg (StageFiniteProbability.law cs).real + ext X + exact (dropTest_eq_true π G hG a ha y (π.transcript X V)).trans + (StageRankLimit.mem_droppedBy_iff _ _ _ _).symm + +/-- Sum over a fixed protected list. The scan list is part of the program, +while the old affine codes, pool, candidate code, and horizon vary. -/ +def partialSum (rules : List ScanRule) (cs : List AffineCode.Data) + (G : List ℕ) (c : AffineCode.Data) (V : ℕ) : ℚ := + (rules.map fun π => partialProbability cs π G c V).sum + +/-- Sum of finite dropped-by-time probabilities over the same protected list. -/ +def dropSum (rules : List ScanRule) (cs : List AffineCode.Data) + (G : List ℕ) (c : AffineCode.Data) (V : ℕ) : ℚ := + (rules.map fun π => dropProbability cs π G c V).sum + +theorem computable_partialSum (rules : List ScanRule) {α : Type*} [Primcodable α] + {cs : α → List AffineCode.Data} {G : α → List ℕ} + {c : α → AffineCode.Data} {V : α → ℕ} + (hcs : Computable cs) (hG : Computable G) (hc : Computable c) (hV : Computable V) : + Computable (fun p => partialSum rules (cs p) (G p) (c p) (V p)) := by + induction rules with + | nil => exact Computable.const 0 + | cons π rules ih => + exact primrec_rat_add.to_comp.comp (computable_partialProbability π hcs hG hc hV) ih + +theorem computable_dropSum (rules : List ScanRule) {α : Type*} [Primcodable α] + {cs : α → List AffineCode.Data} {G : α → List ℕ} + {c : α → AffineCode.Data} {V : α → ℕ} + (hcs : Computable cs) (hG : Computable G) (hc : Computable c) (hV : Computable V) : + Computable (fun p => dropSum rules (cs p) (G p) (c p) (V p)) := by + induction rules with + | nil => exact Computable.const 0 + | cons π rules ih => + exact primrec_rat_add.to_comp.comp (computable_dropProbability π hcs hG hc hV) ih + +theorem partialSum_eq_partialMass (rules : List ScanRule) (cs : List AffineCode.Data) + (G : List ℕ) (hG : G.Nodup) {m r : ℕ} + (a : Entry) (ha : GoodEntry G.length m r a) (y : Fin r → ZMod 2) (V : ℕ) : + (partialSum rules cs G a.2 V : ℝ) = StageRankLimit.partialMass + (StageFiniteProbability.law cs) + (StageCandidate.block G.get hG.injective_get a ha y) rules.get V := by + have hsum : partialSum rules cs G a.2 V = + ∑ i : Fin rules.length, partialProbability cs (rules.get i) G a.2 V := by + unfold partialSum + conv_lhs => rw [← List.ofFn_get rules, List.map_ofFn, List.sum_ofFn] + rfl + rw [hsum, Rat.cast_sum] + apply Finset.sum_congr rfl + intro i _ + exact partialProbability_eq_measureReal cs (rules.get i) G hG a ha y V + +theorem dropSum_eq_dropMass (rules : List ScanRule) (cs : List AffineCode.Data) + (G : List ℕ) (hG : G.Nodup) {m r : ℕ} + (a : Entry) (ha : GoodEntry G.length m r a) (y : Fin r → ZMod 2) (V : ℕ) : + (dropSum rules cs G a.2 V : ℝ) = StageRankLimit.dropMass + (StageFiniteProbability.law cs) + (StageCandidate.block G.get hG.injective_get a ha y) rules.get V := by + have hsum : dropSum rules cs G a.2 V = + ∑ i : Fin rules.length, dropProbability cs (rules.get i) G a.2 V := by + unfold dropSum + conv_lhs => rw [← List.ofFn_get rules, List.map_ofFn, List.sum_ofFn] + rfl + rw [hsum, Rat.cast_sum] + apply Finset.sum_congr rfl + intro i _ + exact dropProbability_eq_measureReal cs (rules.get i) G hG a ha y V + +/-- Ordinary finite data accepted by the two horizon sequences. -/ +abbrev Input := (List AffineCode.Data × List ℕ) × AffineCode.Data + +/-- The actual rational sequence `u` for the horizon search. -/ +def u (rules : List ScanRule) (input : Input) (n : ℕ) : ℚ := + partialSum rules input.1.1 input.1.2 input.2 n + +/-- The actual rational sequence `v` for the horizon search. -/ +def v (rules : List ScanRule) (input : Input) (n : ℕ) : ℚ := + dropSum rules input.1.1 input.1.2 input.2 n + +theorem computable_u (rules : List ScanRule) : Computable₂ (u rules) := + computable_partialSum rules + (Computable.fst.comp (Computable.fst.comp Computable.fst)) + (Computable.snd.comp (Computable.fst.comp Computable.fst)) + (Computable.snd.comp Computable.fst) Computable.snd + +theorem computable_v (rules : List ScanRule) : Computable₂ (v rules) := + computable_dropSum rules + (Computable.fst.comp (Computable.fst.comp Computable.fst)) + (Computable.snd.comp (Computable.fst.comp Computable.fst)) + (Computable.snd.comp Computable.fst) Computable.snd + +/-- The horizon search is partial recursive for the actual finite rank +probabilities, uniformly in the old codes, pool, candidate, and integer advice. -/ +theorem partrec_horizonSearch (rules : List ScanRule) (error : ℚ) : + Partrec (StageHorizon.search error (u rules) (v rules)) := + StageHorizon.partrec_search error (computable_u rules) (computable_v rules) + +/-- The concrete finite probability sequences make the bounded-advice +horizon search halt for every checked candidate satisfying the two actual +high/low mass bounds. Every returned horizon has the required first-drop +tail estimate. -/ +theorem exists_bounded_horizon_search + (rules : List ScanRule) (cs : List AffineCode.Data) + (G : List ℕ) (hG : G.Nodup) {m r : ℕ} + (a : Entry) (ha : GoodEntry G.length m r a) (y : Fin r → ZMod 2) + (H : Fin rules.length → Set Cantor) {error : ℚ} (herror : 0 < error) + [MeasureTheory.IsProbabilityMeasure (StageFiniteProbability.law cs)] + (hhigh : (∑ i : Fin rules.length, (StageFiniteProbability.law cs).real + ((rules.get i).observationMap ⁻¹' H i ∩ + {X | 0 < PoolQuery.missedCount (rules.get i) G.toFinset + ((rules.get i).observationMap X)})) < (error : ℝ)) + (hlow : (∑ i : Fin rules.length, (StageFiniteProbability.law cs).real + ((rules.get i).observationMap ⁻¹' (H i)ᶜ ∩ + LateDropBound.hasDrop (StageCandidate.block G.get hG.injective_get a ha y) + (rules.get i))) < (error : ℝ)) : + ∃ advice, advice ≤ StageHorizon.adviceBound error rules.length ∧ + (StageHorizon.search error (u rules) (v rules) (((cs, G), a.2), advice)).Dom ∧ + ∀ horizon, + horizon ∈ StageHorizon.search error (u rules) (v rules) (((cs, G), a.2), advice) → + StageHorizon.Accepted error (u rules ((cs, G), a.2)) + (v rules ((cs, G), a.2)) advice horizon ∧ + (∑ i : Fin rules.length, (StageFiniteProbability.law cs).real + (StoppingTranscript.rankDropTailEvent + (StageCandidate.block G.get hG.injective_get a ha y) (rules.get i) horizon)) < + 2 * (error : ℝ) := by + have hsubset : (StageCandidate.block G.get hG.injective_get a ha y).support ⊆ + G.toFinset := by + intro p hp + obtain ⟨j, _, rfl⟩ := Finset.mem_image.mp hp + exact List.mem_toFinset.mpr (List.get_mem _ _) + have h := StageRankLimit.exists_bounded_advice_search_of_rank_probabilities + (u := u rules) (v := v rules) herror ((cs, G), a.2) + (StageFiniteProbability.law cs) + (StageCandidate.block G.get hG.injective_get a ha y) rules.get G.toFinset hsubset H + (fun n => partialSum_eq_partialMass rules cs G hG a ha y n) + (fun n => dropSum_eq_dropMass rules cs G hG a ha y n) hhigh hlow + simpa only [Fintype.card_fin] using h + +end Klr.StageRankProbability diff --git a/LeanPool/KLRandomness/StageRankZero.lean b/LeanPool/KLRandomness/StageRankZero.lean new file mode 100644 index 0000000000..37e4ac4fda --- /dev/null +++ b/LeanPool/KLRandomness/StageRankZero.lean @@ -0,0 +1,112 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.StageRank + +/-! +# A finite zero-rank test for concrete sparse blocks + +Partial unread rank can be recognized without computing its numerical value: +the remaining matrix is nonzero, but it is not surjective. Together with the +full-rank bridge, this exact zero test supplies finite predicates for the +stage construction's partial-rank probabilities. +-/ + +@[expose] public section + +noncomputable section + +namespace Klr.StageRank + +open SparseListSearch SparseListWeights SparseSearch SparseListCode StageCandidate +open AffineCode AffineObservation RandomMatrix +open scoped BigOperators + +variable {M m r : ℕ} + +theorem remainingRank_eq_zero_iff_unreadMap_eq_zero (B : AffineBlock) + (π : ScanRule) (v : List Bool) : + B.remainingRank π v = 0 ↔ unreadMap B.matrix (B.observed π v) = 0 := by + rw [AffineBlock.remainingRank, Submodule.finrank_eq_zero, LinearMap.range_eq_bot] + +/-- Rank zero means that every unqueried pool column is zero. -/ +theorem remainingRank_eq_zero_iff_columns + (e : Fin M → ℕ) (he : Function.Injective e) (a : Entry) + (ha : GoodEntry M m r a) (y : Fin r → ZMod 2) + (π : ScanRule) (v : List Bool) : + (block e he a ha y).remainingRank π v = 0 ↔ + ∀ j : Fin M, j ∈ unreadPool e π v → columns a M r j = 0 := by + classical + rw [remainingRank_eq_zero_iff_unreadMap_eq_zero] + constructor + · intro hzero j hj + by_cases hs : j ∈ support M a + · let p : (block e he a ha y).support := positionEquiv e he a ⟨j, hs⟩ + have hp : p ∉ (block e he a ha y).observed π v := + (mem_unreadPool e π v j).mp hj + have h := (unreadMap_single (block e he a ha y).matrix + ((block e he a ha y).observed π v) p hp).trans + (block_matrix_single e he a ha y ⟨j, hs⟩) + rw [hzero, LinearMap.zero_apply] at h + exact h.symm + · exact columns_zero_off_support ha hs + · intro hcols + apply LinearMap.ext + intro x + change (∑ j : support M a, + (extendUnread ((block e he a ha y).observed π v) x) + (positionEquiv e he a j) • columns a M r j.val) = 0 + apply Finset.sum_eq_zero + intro j _ + by_cases hj : e j.val ∈ π.queriedPositions v + · have ho : positionEquiv e he a j ∈ (block e he a ha y).observed π v := hj + rw [extendUnread_apply_of_mem _ x _ ho, zero_smul] + · rw [hcols j.val ((mem_unreadPool e π v j.val).mpr hj), smul_zero] + +/-- The actual Boolean masked matrix is zero exactly when all selected +columns vanish; dimensions are supplied by the successful entry verifier. -/ +theorem masked_matrix_eq_zero_iff_columns {a : Entry} (ha : GoodEntry M m r a) + (d : List Bool) : + matrix (maskCode a.2 d) = 0 ↔ + ∀ j : Fin M, j ∈ maskSet M d → columns a M r j = 0 := by + have hw := ha.2.2.1 + have hr := ha.2.2.2.1 + cases hw + cases hr + rw [matrix_maskCode] + constructor + · intro h j hj + have hd := (mem_maskSet (width a.2) d j).mp hj + funext i + change matrix a.2 i j = (0 : ZMod 2) + have hi := congrFun (congrFun h i) j + change (if d.getD j.val false then matrix a.2 i j else 0) = (0 : ZMod 2) at hi + simpa only [hd, Bool.true_eq, ↓reduceIte] using hi + · intro h + funext i j + change (if d.getD j.val false then matrix a.2 i j else 0) = (0 : ZMod 2) + cases hd : d.getD j.val false with + | false => rfl + | true => + have hz := congrFun (h j ((mem_maskSet _ _ _).mpr hd)) i + change matrix a.2 i j = (0 : ZMod 2) at hz + simpa only [Bool.true_eq, ↓reduceIte] using hz + +/-- Exact finite zero-rank test for the affine block embedded on a concrete pool. -/ +theorem remainingRank_eq_zero_iff_masked_matrix_eq_zero + (e : Fin M → ℕ) (he : Function.Injective e) (a : Entry) + (ha : GoodEntry M m r a) (y : Fin r → ZMod 2) + (π : ScanRule) (v : List Bool) : + (block e he a ha y).remainingRank π v = 0 ↔ + matrix (maskCode a.2 (mask (unreadPool e π v))) = 0 := by + rw [remainingRank_eq_zero_iff_columns e he a ha y π v, + masked_matrix_eq_zero_iff_columns ha, maskSet_mask] + +end Klr.StageRank diff --git a/LeanPool/KLRandomness/StageRationalError.lean b/LeanPool/KLRandomness/StageRationalError.lean new file mode 100644 index 0000000000..a3bab73ad1 --- /dev/null +++ b/LeanPool/KLRandomness/StageRationalError.lean @@ -0,0 +1,47 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.StageErrorBudget +import Mathlib.Tactic.NormNum +import Mathlib.Tactic.Positivity + +/-! +# Rational errors for the stage search + +The finite verifier uses rational arithmetic. Its positive rational error is +identified here with the ENNReal dyadic budget used by the final stage API. +-/ + +@[expose] public section + +namespace Klr.StageErrorBudget + +open scoped ENNReal + +/-- The executable rational presentation of the stage error. -/ +def rational (n : ℕ) : ℚ := (1 / 2 : ℚ) ^ n / 100 + +theorem rational_pos (n : ℕ) : 0 < rational n := by unfold rational; positivity + +theorem rational_cast_pos (n : ℕ) : (0 : ℝ) < rational n := by + exact_mod_cast rational_pos n + +theorem ofReal_rational (n : ℕ) : ENNReal.ofReal (rational n : ℝ) = error n := by + unfold rational error + push_cast + rw [ENNReal.ofReal_div_of_pos (by norm_num), ENNReal.ofReal_pow (by positivity), + ENNReal.ofReal_div_of_pos (by norm_num)] + norm_num + +theorem ofReal_mul_rational (k n : ℕ) : + ENNReal.ofReal ((k : ℝ) * (rational n : ℝ)) = (k : ℝ≥0∞) * error n := by + rw [ENNReal.ofReal_mul (by positivity), ofReal_rational, ENNReal.ofReal_natCast] + +end Klr.StageErrorBudget diff --git a/LeanPool/KLRandomness/StageReconstruction.lean b/LeanPool/KLRandomness/StageReconstruction.lean new file mode 100644 index 0000000000..d3b10fb3a2 --- /dev/null +++ b/LeanPool/KLRandomness/StageReconstruction.lean @@ -0,0 +1,162 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.StageSyndromeObjective +public import LeanPool.KLRandomness.StageRankProbability +public import LeanPool.KLRandomness.SparseListConstruction +public import LeanPool.KLRandomness.PoolSearch +public import LeanPool.KLRandomness.AffineProgramLength + +/-! +# One fixed reconstruction program for a whole stage + +All earlier affine codes, protected strategies, rational parameters, and the +pool program form a fixed header. The variable input is only the trial rank, +the candidate-list index, and bounded integer horizon advice. Pool and sparse +list construction, horizon search, syndrome minimization, and certified code +reconstruction are composed as actual partial recursive computations. +-/ + +@[expose] public section + +noncomputable section + +namespace Klr.StageReconstruction + +open SparseListSearch + +/-- Trial rank, list position, and bounded integer horizon advice. -/ +abbrev Input := ℕ × (ℕ × ℕ) + +/-- Decode a natural number as a list of positions, using the empty list on failure. -/ +def decodePool (n : ℕ) : List ℕ := + (@Encodable.decode (List ℕ) (inferInstance : Primcodable (List ℕ)).toEncodable n).getD [] + +theorem computable_decodePool : Computable decodePool := + Primrec.option_getD_default.to_comp.comp Computable.decode + +@[simp] theorem decodePool_encodePool (G : List ℕ) : + decodePool (PoolAdvice.encodePool G) = G := by + simp [decodePool, PoolAdvice.encodePool] + +/-- Execute the fixed pool program at the trial size `r⁸`. -/ +def readPool (poolProgram : Nat.Partrec.Code) (r : ℕ) : Part (List ℕ) := + (poolProgram.eval (r ^ 8)).map decodePool + +theorem partrec_readPool (poolProgram : Nat.Partrec.Code) : Partrec (readPool poolProgram) := + (Nat.Partrec.Code.eval_part.comp (Computable.const poolProgram) + (SparseListConstruction.computable_pow_const 8)).map + (computable_decodePool.comp Computable.snd) + +theorem mem_readPool {poolProgram : Nat.Partrec.Code} {r : ℕ} {G : List ℕ} + (hG : PoolAdvice.encodePool G ∈ poolProgram.eval (r ^ 8)) : G ∈ readPool poolProgram r := by + simpa only [readPool, decodePool_encodePool] using Part.mem_map decodePool hG + +/-- Search the horizon and recover the syndrome and certified output from +an already selected concrete candidate. -/ +def atCandidate (rules : List BettingStrategy) (cs : List AffineCode.Data) (error : ℚ) + (p : (List ℕ × Entry) × ℕ) : Part AffineCode.Data := + (StageHorizon.search error + (StageRankProbability.u (rules.map (fun s => s.normalize.scan))) + (StageRankProbability.v (rules.map (fun s => s.normalize.scan))) + (((cs, p.1.1), p.1.2.2), p.2)).bind fun V => + StageSyndromeObjective.finish rules cs (p.1, V) + +theorem partrec_atCandidate (rules : List BettingStrategy) + (cs : List AffineCode.Data) (error : ℚ) : Partrec (atCandidate rules cs error) := by + have hG : Computable (fun p : (List ℕ × Entry) × ℕ => p.1.1) := + Computable.fst.comp Computable.fst + have hc : Computable (fun p : (List ℕ × Entry) × ℕ => p.1.2.2) := + Computable.snd.comp (Computable.snd.comp Computable.fst) + have hi := (((Computable.const cs).pair hG).pair hc).pair Computable.snd + have hs := (StageHorizon.partrec_search error + (StageRankProbability.computable_u (rules.map (fun s => s.normalize.scan))) + (StageRankProbability.computable_v (rules.map (fun s => s.normalize.scan)))).comp hi + have hf : Partrec (fun p : ((List ℕ × Entry) × ℕ) × ℕ => + StageSyndromeObjective.finish rules cs (p.1.1, p.2)) := + (StageSyndromeObjective.partrec_finish rules cs).comp + ((Computable.fst.comp Computable.fst).pair Computable.snd) + exact hs.bind hf.to₂ + +/-- Generate the same complete sparse list as in candidate selection and +retrieve its supplied list position. -/ +def afterPool (rules : List BettingStrategy) (cs : List AffineCode.Data) + (error τ θ : ℚ) (p : Input × List ℕ) : Part AffineCode.Data := + (SparseListConstruction.construct τ θ p.1.1).bind fun L => + atCandidate rules cs error ((p.2, L.getD p.1.2.1 default), p.1.2.2) + +theorem partrec_afterPool (rules : List BettingStrategy) (cs : List AffineCode.Data) + (error τ θ : ℚ) : Partrec (afterPool rules cs error τ θ) := by + have hs : Partrec (fun p : Input × List ℕ => SparseListConstruction.construct τ θ p.1.1) := + (SparseListConstruction.partrec_construct τ θ).comp + (Computable.fst.comp Computable.fst) + have hG : Computable (fun p : (Input × List ℕ) × CodeList => p.1.2) := + Computable.snd.comp Computable.fst + have hq : Computable (fun p : (Input × List ℕ) × CodeList => p.1.1.2.1) := + Computable.fst.comp (Computable.snd.comp (Computable.fst.comp Computable.fst)) + have hb : Computable (fun p : (Input × List ℕ) × CodeList => p.1.1.2.2) := + Computable.snd.comp (Computable.snd.comp (Computable.fst.comp Computable.fst)) + have ha := (Primrec.list_getD (default : Entry)).to_comp.comp Computable.snd hq + have hf := (partrec_atCandidate rules cs error).comp ((hG.pair ha).pair hb) + exact hs.bind hf.to₂ + +/-- The actual complete fixed-stage reconstruction computation. -/ +def run (rules : List BettingStrategy) (cs : List AffineCode.Data) + (poolProgram : Nat.Partrec.Code) (error τ θ : ℚ) (input : Input) : Part AffineCode.Data := + (readPool poolProgram input.1).bind fun G => afterPool rules cs error τ θ (input, G) + +theorem partrec_run (rules : List BettingStrategy) (cs : List AffineCode.Data) + (poolProgram : Nat.Partrec.Code) (error τ θ : ℚ) : + Partrec (run rules cs poolProgram error τ θ) := + ((partrec_readPool poolProgram).comp Computable.fst).bind + (partrec_afterPool rules cs error τ θ).to₂ + +/-- Decode the explicit nested natural-number pairing used in the length bound. -/ +def inputOfNat (n : ℕ) : Input := + (n.unpair.1, (n.unpair.2.unpair.1, n.unpair.2.unpair.2)) + +theorem computable_inputOfNat : Computable inputOfNat := + (Computable.fst.comp Primrec.unpair.to_comp).pair + (Primrec.unpair.to_comp.comp (Computable.snd.comp Primrec.unpair.to_comp)) + +@[simp] theorem inputOfNat_pair (r q b : ℕ) : + inputOfNat (Nat.pair r (Nat.pair q b)) = (r, (q, b)) := by simp [inputOfNat] + +/-- A single actual code, chosen before the rank and both advice values, +implements every successful stage reconstruction. -/ +theorem exists_fixed_program (rules : List BettingStrategy) (cs : List AffineCode.Data) + (poolProgram : Nat.Partrec.Code) (error τ θ : ℚ) : + ∃ e : Nat.Partrec.Code, ∀ r q b, + AffineDescription.run (AffineDescription.programFor e (Nat.pair r (Nat.pair q b))) = + run rules cs poolProgram error τ θ (r, (q, b)) := by + have hp := (partrec_run rules cs poolProgram error τ θ).comp computable_inputOfNat + obtain ⟨e, he⟩ := Nat.Partrec.Code.exists_code.mp hp + refine ⟨e, fun r q b => ?_⟩ + rw [AffineDescription.run_programFor, he] + simp only [Encodable.decode_nat, Part.coe_some, Part.bind_some, inputOfNat_pair, Part.map_map] + exact Part.map_id' (fun _ => AffineDescription.decodeOutput_encode _) _ + +/-- Executing the composite program agrees with independently established +pool, list, horizon, and final-output witnesses. -/ +theorem mem_run_of_witnesses (rules : List BettingStrategy) (cs : List AffineCode.Data) + (poolProgram : Nat.Partrec.Code) (error τ θ : ℚ) + {r q b : ℕ} {G : List ℕ} {L : CodeList} {V : ℕ} {c : AffineCode.Data} + (hG : PoolAdvice.encodePool G ∈ poolProgram.eval (r ^ 8)) + (hL : L ∈ SparseListConstruction.construct τ θ r) + (hV : V ∈ StageHorizon.search error + (StageRankProbability.u (rules.map (fun s => s.normalize.scan))) + (StageRankProbability.v (rules.map (fun s => s.normalize.scan))) + (((cs, G), (L.getD q default).2), b)) + (hc : c ∈ StageSyndromeObjective.finish rules cs ((G, L.getD q default), V)) : + c ∈ run rules cs poolProgram error τ θ (r, (q, b)) := by + exact Part.mem_bind (mem_readPool hG) + (Part.mem_bind hL (Part.mem_bind hV hc)) + +end Klr.StageReconstruction diff --git a/LeanPool/KLRandomness/StageRecursion.lean b/LeanPool/KLRandomness/StageRecursion.lean new file mode 100644 index 0000000000..ede29483f5 --- /dev/null +++ b/LeanPool/KLRandomness/StageRecursion.lean @@ -0,0 +1,218 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.StageRecursionData +public import LeanPool.KLRandomness.StageRationalError + +/-! +# Dependent stage recursion and passage to the infinite block sequence + +Starting from a concrete one-step extension theorem, dependent recursion +builds coherent finite histories. Their diagonal sequence has disjoint +supports, satisfies the actual `StageEstimates` for each eventually protected +strategy, and has a short exact affine program at every test level. + +The final gluing theorem retains its one-step existence premise explicitly. +The construction-specific extension theorem is supplied separately. +-/ + +@[expose] public section + +noncomputable section + +namespace Klr.StageRecursion + +open MeasureTheory ProbabilityTheory +open scoped ENNReal + +/-- A selected actual extension of one finite history. -/ +structure Chosen (s : ℕ → BettingStrategy) (H : ℕ → Set Cantor) + {n : ℕ} (h : History n) where + /-- The affine block selected for this step of the recursion. -/ + block : AffineBlock + /-- The finite horizon selected together with the block. -/ + horizon : ℕ + specification : Step s H h.blocks n (h.cutoff s) + (StageErrorBudget.rational n) block horizon + +variable (s : ℕ → BettingStrategy) (H : ℕ → Set Cantor) + (hstep : ∀ (old : ℕ → AffineBlock), + Pairwise (fun i j => Disjoint (old i).support (old j).support) → + ∀ n z : ℕ, ∃ (C : AffineBlock) (V : ℕ), + Step s H old n z (StageErrorBudget.rational n) C V) + +/-- Choice is used only to assemble the mathematical sequence from the +proved nonempty family of successful finite extensions. -/ +def chooseNext {n : ℕ} (h : History n) : Chosen s H h := + Classical.choice (by + obtain ⟨C, V, hCV⟩ := hstep h.blocks h.disjoint n (h.cutoff s) + exact ⟨⟨C, V, hCV⟩⟩) + +/-- The recursively constructed, padded finite history. -/ +def histories : (n : ℕ) → History n + | 0 => History.empty + | n + 1 => + let h := histories n + let c := chooseNext s H hstep h + h.extend s c.block c.horizon c.specification.above + +/-- The actual new block selected at each stage. -/ +def blocks (n : ℕ) : AffineBlock := (chooseNext s H hstep (histories s H hstep n)).block + +/-- The common protected-scan horizon selected at each stage. -/ +def horizons (n : ℕ) : ℕ := (chooseNext s H hstep (histories s H hstep n)).horizon + +theorem histories_succ_blocks (n : ℕ) : + (histories s H hstep (n + 1)).blocks = + Function.update (histories s H hstep n).blocks n (blocks s H hstep n) := rfl + +theorem histories_succ_horizon (n : ℕ) : + (histories s H hstep (n + 1)).horizon = + Function.update (histories s H hstep n).horizon n (horizons s H hstep n) := rfl + +/-- Every finite history is the exact initial segment of the diagonal blocks. -/ +theorem histories_blocks_eq (n j : ℕ) (hj : j < n) : + (histories s H hstep n).blocks j = blocks s H hstep j := by + induction n with + | zero => omega + | succ n ih => + rw [histories_succ_blocks] + by_cases hjn : j = n + · subst j + exact Function.update_self _ _ _ + · rw [Function.update_of_ne hjn] + exact ih (by omega) + +/-- The selected horizons have the same coherence property. -/ +theorem histories_horizon_eq (n j : ℕ) (hj : j < n) : + (histories s H hstep n).horizon j = horizons s H hstep j := by + induction n with + | zero => omega + | succ n ih => + rw [histories_succ_horizon] + by_cases hjn : j = n + · subst j + exact Function.update_self _ _ _ + · rw [Function.update_of_ne hjn] + exact ih (by omega) + +/-- All preceding finite-stage laws agree exactly with the laws of the +diagonal sequence, including laws strictly before the latest history. -/ +theorem histories_law_eq (n a : ℕ) (ha : a ≤ n) : + PrefixStage.law (histories s H hstep n).blocks a = + PrefixStage.law (blocks s H hstep) a := by + apply congrArg AffineBlock.finiteStageLaw + funext j + exact histories_blocks_eq s H hstep n j.val (lt_of_lt_of_le j.isLt ha) + +theorem blocks_pairwise : + Pairwise (fun i j => Disjoint (blocks s H hstep i).support + (blocks s H hstep j).support) := by + intro i j hij + have hi : i < max i j + 1 := Nat.lt_succ_of_le (le_max_left _ _) + have hj : j < max i j + 1 := Nat.lt_succ_of_le (le_max_right _ _) + have hd := (histories s H hstep (max i j + 1)).disjoint hij + dsimp only at hd + rwa [histories_blocks_eq s H hstep _ i hi, histories_blocks_eq s H hstep _ j hj] at hd + +theorem selected_step (n : ℕ) : + Step s H (histories s H hstep n).blocks n ((histories s H hstep n).cutoff s) + (StageErrorBudget.rational n) (blocks s H hstep n) (horizons s H hstep n) := + (chooseNext s H hstep (histories s H hstep n)).specification + +/-- The early wager of one block depends only on that block and its horizon. -/ +theorem earlyWager_single (B : ℕ → AffineBlock) (π : ScanRule) + (w : List Bool → ℝ) (V : ℕ → ℕ) (j : ℕ) : + EarlyLateWagers.earlyWager (fun _ => B j) π w (fun _ => V j) 0 = + EarlyLateWagers.earlyWager B π w V j := rfl + +/-- Later blocks avoid every branch through every earlier protected horizon. -/ +theorem horizon_avoidance (i j k : ℕ) (hij : i ≤ j) (hjk : j < k) + (v : List Bool) (hv : v.length = horizons s H hstep j) : + (blocks s H hstep k).UnreadFullRank (s i).normalize.scan v := by + apply HorizonAvoidance.unreadFullRank_of_queryBound_le _ _ (horizons s H hstep j) _ v hv.le + intro q hq + have hb := History.queryBound_le_cutoff s (histories s H hstep k) ⟨j, hjk⟩ i hij + rw [histories_horizon_eq s H hstep k j hjk] at hb + exact hb.trans ((selected_step s H hstep k).above q hq) + +/-- The finite construction yields all actual stage estimates for strategy +`i` from stage `i` onward. -/ +theorem stageEstimates (hH : ∀ i, MeasurableSet (H i)) (i : ℕ) : + StageEstimates (blocks s H hstep) (s i).normalize.scan + (s i).normalize.capital.wager (horizons s H hstep) (H i) i := by + refine ⟨hH i, ?_, ?_, ?_, ?_, ?_⟩ + · intro j hij v hv k hjk + exact horizon_avoidance s H hstep i j k hij hjk v hv + · intro j hij + have h := (selected_step s H hstep j).early_and_partial i hij + rw [histories_law_eq s H hstep j j le_rfl, + ← PrefixStage.law_succ_eq_cond, earlyWager_single] at h + have hb : ENNReal.ofReal (4 * (StageErrorBudget.rational j : ℝ)) = + 4 * StageErrorBudget.error j := by + simpa only [Nat.cast_ofNat] using StageErrorBudget.ofReal_mul_rational 4 j + rwa [hb] at h + · intro j hij + have h := (selected_step s H hstep j).first_drop_tail i hij + rw [histories_law_eq s H hstep j j le_rfl, + ← PrefixStage.law_succ_eq_cond] at h + have hb : ENNReal.ofReal (2 * (StageErrorBudget.rational j : ℝ)) = + 2 * StageErrorBudget.error j := by + simpa only [Nat.cast_ofNat] using StageErrorBudget.ofReal_mul_rational 2 j + rwa [hb] at h + · intro j hij + have h := (selected_step s H hstep j).high_no_drop i hij + rwa [histories_law_eq s H hstep j j le_rfl, StageErrorBudget.ofReal_rational] at h + · intro j hij k hjk + have h := (selected_step s H hstep k).earlier_low_drop + (j + 1) (by omega) i (by omega) + rwa [histories_law_eq s H hstep k (j + 1) (by omega), + StageErrorBudget.ofReal_rational] at h + +/-- Stage `n` supplies the exact short affine program required at test level `n`. -/ +theorem description (n : ℕ) : ∃ (p : List Bool) (c : AffineCode.Data), + c ∈ AffineDescription.run p ∧ AffineCode.valid c = true ∧ + AffineCode.rank c = (blocks s H hstep n).rank ∧ + 2 * p.length + n + 1 ≤ AffineCode.rank c ∧ + AffineCode.event c = (blocks s H hstep n).event := + (selected_step s H hstep n).description + +include hstep in +/-- The concrete one-stage extension relation glues to a full sequence +with the probabilistic estimates and exact description obligations discharged. -/ +theorem exists_sequence (hH : ∀ i, MeasurableSet (H i)) : + ∃ (B : ℕ → AffineBlock) (V : ℕ → ℕ), + Pairwise (fun i j => Disjoint (B i).support (B j).support) ∧ + (∀ i, StageEstimates B (s i).normalize.scan (s i).normalize.capital.wager V (H i) i) ∧ + ∀ n : ℕ, ∃ (p : List Bool) (c : AffineCode.Data), + c ∈ AffineDescription.run p ∧ AffineCode.valid c = true ∧ + 2 * p.length + n + 1 ≤ AffineCode.rank c ∧ AffineCode.event c = (B n).event := by + refine ⟨blocks s H hstep, horizons s H hstep, blocks_pairwise s H hstep, + stageEstimates s H hstep hH, ?_⟩ + intro n + obtain ⟨p, c, hp, hc, _, hb, he⟩ := description s H hstep n + exact ⟨p, c, hp, hc, hb, he⟩ + +include hstep in +/-- Conditional gluing to separation: its sole construction premise is +the explicit one-stage extension theorem for the fixed partitions. -/ +theorem exists_separating_of_steps (hs : Function.Surjective s) + (hH : ∀ i, MeasurableSet (H i)) : + ∃ X : Cantor, KolmogorovLovelandRandom X ∧ ¬MartinLofRandom X := by + obtain ⟨B, V, hdis, hest, hprogram⟩ := exists_sequence s H hstep hH + apply exists_separating_of_stage_estimates_and_exact_affine_programs B hdis V + · intro t + obtain ⟨i, rfl⟩ := hs t + exact ⟨H i, i, hest i⟩ + · intro n + obtain ⟨p, c, hp, hc, hb, he⟩ := hprogram n + exact ⟨n, p, c, hp, hc, hb, he⟩ + +end Klr.StageRecursion diff --git a/LeanPool/KLRandomness/StageRecursionData.lean b/LeanPool/KLRandomness/StageRecursionData.lean new file mode 100644 index 0000000000..c66adde0c7 --- /dev/null +++ b/LeanPool/KLRandomness/StageRecursionData.lean @@ -0,0 +1,160 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.StageStep +public import LeanPool.KLRandomness.HorizonAvoidance + +/-! +# Finite construction histories and their avoidance cutoffs + +A finite history is represented by natural-number indexed blocks and +horizons, with explicit empty padding beyond its length. Its cutoff covers +every old support and every query on every branch through each old protected +horizon. Adding a support above that cutoff preserves disjointness and all +the required future horizon avoidance. +-/ + +@[expose] public section + +noncomputable section + +namespace Klr.StageRecursion + +open scoped BigOperators + +/-- Empty padding imposes no equation and uses no coordinates. -/ +def emptyBlock : AffineBlock where + support := ∅ + rank := 0 + matrix := 0 + fullRank := fun y => ⟨0, Subsingleton.elim _ y⟩ + syndrome := 0 + +@[simp] theorem emptyBlock_support : emptyBlock.support = ∅ := rfl + +/-- Finite history with explicit harmless padding after its last stage. -/ +structure History (n : ℕ) where + /-- The affine blocks selected so far, extended by empty blocks. -/ + blocks : ℕ → AffineBlock + /-- Finite query horizons recorded by earlier stages. -/ + horizon : ℕ → ℕ + disjoint : Pairwise (fun i j => Disjoint (blocks i).support (blocks j).support) + blocks_tail : ∀ k, n ≤ k → blocks k = emptyBlock + horizon_tail : ∀ k, n ≤ k → horizon k = 0 + +namespace History + +/-- The initial history has no blocks or protected horizons. -/ +def empty : History 0 where + blocks := fun _ => emptyBlock + horizon := fun _ => 0 + disjoint := by intro i j hij; simp + blocks_tail := fun _ _ => rfl + horizon_tail := fun _ _ => rfl + +variable {n : ℕ} + +/-- One finite contribution to the avoidance cutoff. At stage `j`, strategies +`0, ..., j` must be protected through that stage's common horizon. -/ +def boundTerm (s : ℕ → BettingStrategy) (h : History n) (j : Fin n) : ℕ := + (h.blocks j.val).support.sup id + + ∑ i : Fin (j.val + 1), HorizonAvoidance.queryBound (s i.val).normalize.scan + (h.horizon j.val) + +/-- A strict bound for all old support coordinates, and an upper bound for +all earlier protected all-branch query bounds. -/ +def cutoff (s : ℕ → BettingStrategy) (h : History n) : ℕ := + (∑ j : Fin n, boundTerm s h j) + 1 + +theorem support_lt_cutoff (s : ℕ → BettingStrategy) (h : History n) + (j : Fin n) {q : ℕ} (hq : q ∈ (h.blocks j.val).support) : q < cutoff s h := by + have hs := Finset.le_sup (f := id) hq + change q ≤ (h.blocks j.val).support.sup id at hs + have ht : boundTerm s h j ≤ ∑ k : Fin n, boundTerm s h k := + Finset.single_le_sum (fun _ _ => Nat.zero_le _) (Finset.mem_univ j) + unfold cutoff boundTerm at * + omega + +theorem queryBound_le_cutoff (s : ℕ → BettingStrategy) (h : History n) + (j : Fin n) (i : ℕ) (hi : i ≤ j.val) : + HorizonAvoidance.queryBound (s i).normalize.scan (h.horizon j.val) ≤ cutoff s h := by + let f : Fin (j.val + 1) → ℕ := fun k => + HorizonAvoidance.queryBound (s k.val).normalize.scan (h.horizon j.val) + let ii : Fin (j.val + 1) := ⟨i, Nat.lt_succ_of_le hi⟩ + have hs : f ii ≤ ∑ k : Fin (j.val + 1), f k := + Finset.single_le_sum (f := f) (s := Finset.univ) (fun _ _ => Nat.zero_le _) + (Finset.mem_univ ii) + change HorizonAvoidance.queryBound (s i).normalize.scan (h.horizon j.val) ≤ + ∑ k : Fin (j.val + 1), HorizonAvoidance.queryBound (s k.val).normalize.scan + (h.horizon j.val) at hs + have ht : boundTerm s h j ≤ ∑ k : Fin n, boundTerm s h k := + Finset.single_le_sum (fun _ _ => Nat.zero_le _) (Finset.mem_univ j) + unfold cutoff boundTerm at * + omega + +/-- A support above the cutoff is disjoint from every old block, including +the empty padding. -/ +theorem disjoint_of_above (s : ℕ → BettingStrategy) (h : History n) + (C : AffineBlock) (hC : ∀ q ∈ C.support, cutoff s h ≤ q) (j : ℕ) : + Disjoint (h.blocks j).support C.support := by + by_cases hj : j < n + · apply Finset.disjoint_left.mpr + intro q hq hqC + exact (not_lt_of_ge (hC q hqC)) (support_lt_cutoff s h ⟨j, hj⟩ hq) + · rw [h.blocks_tail j (Nat.le_of_not_gt hj)] + simp + +/-- Extend a finite history by its next block and common horizon. -/ +def extend (s : ℕ → BettingStrategy) (h : History n) (C : AffineBlock) (V : ℕ) + (hC : ∀ q ∈ C.support, cutoff s h ≤ q) : History (n + 1) where + blocks := Function.update h.blocks n C + horizon := Function.update h.horizon n V + disjoint := by + intro i j hij + by_cases hi : i = n + · subst i + have hj : j ≠ n := Ne.symm hij + simpa only [Function.update_self, Function.update_of_ne hj] using + (disjoint_of_above s h C hC j).symm + · by_cases hj : j = n + · subst j + simpa only [Function.update_self, Function.update_of_ne hi] using + disjoint_of_above s h C hC i + · simpa only [Function.update_of_ne hi, Function.update_of_ne hj] using h.disjoint hij + blocks_tail := by + intro k hk + rw [Function.update_of_ne (by omega : k ≠ n)] + exact h.blocks_tail k (by omega) + horizon_tail := by + intro k hk + rw [Function.update_of_ne (by omega : k ≠ n)] + exact h.horizon_tail k (by omega) + +@[simp] theorem extend_blocks_self (s : ℕ → BettingStrategy) (h : History n) + (C : AffineBlock) (V : ℕ) (hC : ∀ q ∈ C.support, cutoff s h ≤ q) : + (extend s h C V hC).blocks n = C := Function.update_self _ _ _ + +@[simp] theorem extend_horizon_self (s : ℕ → BettingStrategy) (h : History n) + (C : AffineBlock) (V : ℕ) (hC : ∀ q ∈ C.support, cutoff s h ≤ q) : + (extend s h C V hC).horizon n = V := Function.update_self _ _ _ + +theorem extend_blocks_of_lt (s : ℕ → BettingStrategy) (h : History n) + (C : AffineBlock) (V : ℕ) (hC : ∀ q ∈ C.support, cutoff s h ≤ q) + {j : ℕ} (hj : j < n) : (extend s h C V hC).blocks j = h.blocks j := + Function.update_of_ne (Nat.ne_of_lt hj) _ _ + +theorem extend_horizon_of_lt (s : ℕ → BettingStrategy) (h : History n) + (C : AffineBlock) (V : ℕ) (hC : ∀ q ∈ C.support, cutoff s h ≤ q) + {j : ℕ} (hj : j < n) : (extend s h C V hC).horizon j = h.horizon j := + Function.update_of_ne (Nat.ne_of_lt hj) _ _ + +end History + +end Klr.StageRecursion diff --git a/LeanPool/KLRandomness/StageStep.lean b/LeanPool/KLRandomness/StageStep.lean new file mode 100644 index 0000000000..964fea86f8 --- /dev/null +++ b/LeanPool/KLRandomness/StageStep.lean @@ -0,0 +1,59 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.AffineDescriptionSeparation + +/-! +# The concrete relation between two successive construction stages + +The relation records estimates for one actual new affine block under the +actual preceding finite-stage laws. The old sequence is only consulted +before `n`; later blocks may be empty padding. A successful step also +includes a short, successfully evaluated exact affine description. +-/ + +@[expose] public section + +namespace Klr.StageRecursion + +open MeasureTheory ProbabilityTheory +open scoped ENNReal + +/-- One stage's complete mathematical output. The fixed Borel partition +is shared across all stages, and the protected strategies are `0, ..., n`. -/ +structure Step (s : ℕ → BettingStrategy) (H : ℕ → Set Cantor) + (old : ℕ → AffineBlock) (n z : ℕ) (error : ℚ) + (C : AffineBlock) (V : ℕ) : Prop where + above : ∀ q ∈ C.support, z ≤ q + early_and_partial : ∀ i, i ≤ n → + (∫⁻ X, ENNReal.ofReal (EarlyLateWagers.earlyWager (fun _ => C) + (s i).normalize.scan (s i).normalize.capital.wager (fun _ => V) 0 X) + ∂cond (PrefixStage.law old n) C.event) + + cond (PrefixStage.law old n) C.event + (LateDropBound.partialEvent C (s i).normalize.scan V) ≤ + ENNReal.ofReal (4 * (error : ℝ)) + first_drop_tail : ∀ i, i ≤ n → + cond (PrefixStage.law old n) C.event + (StoppingTranscript.rankDropTailEvent C (s i).normalize.scan V) ≤ + ENNReal.ofReal (2 * (error : ℝ)) + high_no_drop : ∀ i, i ≤ n → + PrefixStage.law old n + ((s i).normalize.scan.observationMap ⁻¹' H i ∩ + NoDrop.noDropEvent C (s i).normalize.scan) ≤ ENNReal.ofReal (error : ℝ) + earlier_low_drop : ∀ a, a ≤ n → ∀ i, i ≤ n → + PrefixStage.law old a + ((s i).normalize.scan.observationMap ⁻¹' (H i)ᶜ ∩ + LateDropBound.hasDrop C (s i).normalize.scan) ≤ ENNReal.ofReal (error : ℝ) + description : ∃ (p : List Bool) (c : AffineCode.Data), + c ∈ AffineDescription.run p ∧ AffineCode.valid c = true ∧ + AffineCode.rank c = C.rank ∧ + 2 * p.length + n + 1 ≤ AffineCode.rank c ∧ AffineCode.event c = C.event + +end Klr.StageRecursion diff --git a/LeanPool/KLRandomness/StageSyndrome.lean b/LeanPool/KLRandomness/StageSyndrome.lean new file mode 100644 index 0000000000..72646ffeae --- /dev/null +++ b/LeanPool/KLRandomness/StageSyndrome.lean @@ -0,0 +1,117 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.AffineFamily +public import LeanPool.KLRandomness.StageSyndromeComputable +public import Mathlib.Algebra.Order.BigOperators.Expect +import Mathlib.Tactic.Linarith +import Mathlib.Tactic.Positivity +import Mathlib.Tactic.Push + +/-! +# Averaging the actual conditional laws over all syndromes + +For a new full-rank block disjoint from all old blocks, every syndrome has +probability `2⁻ʳ` under the old finite-stage law. The equally weighted average +of the new conditional expectations is therefore exactly the old expectation. +This is the measure identity behind the computable syndrome minimization. +-/ + +@[expose] public section + +namespace Klr.StageSyndrome + +open MeasureTheory ProbabilityTheory AffineBlock FiniteMeasure +open scoped BigOperators + +/-- Vary only the syndrome of the candidate block. -/ +def withSyndrome (B : AffineBlock) (y : Fin B.rank → ZMod 2) : AffineBlock := + { B with syndrome := y } + +@[simp] theorem withSyndrome_support (B : AffineBlock) (y : Fin B.rank → ZMod 2) : + (withSyndrome B y).support = B.support := rfl + +@[simp] theorem withSyndrome_rank (B : AffineBlock) (y : Fin B.rank → ZMod 2) : + (withSyndrome B y).rank = B.rank := rfl + +theorem mem_withSyndrome_event (B : AffineBlock) (y : Fin B.rank → ZMod 2) (X : Cantor) : + X ∈ (withSyndrome B y).event ↔ + B.matrix (coordinateValues (fun i : B.support => i.val) X) = y := Iff.rfl + +/-- The syndrome events form an exact finite partition on every input. -/ +theorem sum_syndrome_indicators (B : AffineBlock) (f : Cantor → ℝ) (X : Cantor) : + (∑ y : Fin B.rank → ZMod 2, (withSyndrome B y).event.indicator f X) = f X := by + classical + let y₀ := B.matrix (coordinateValues (fun i : B.support => i.val) X) + rw [Finset.sum_eq_single y₀] + · exact Set.indicator_of_mem rfl f + · intro y _ hne + apply Set.indicator_of_notMem + intro h + exact hne ((mem_withSyndrome_event B y X).mp h).symm + · simp + +theorem sum_setIntegral_syndromes (B : AffineBlock) {μ : Measure Cantor} + {f : Cantor → ℝ} (hf : Integrable f μ) : + (∑ y : Fin B.rank → ZMod 2, ∫ X in (withSyndrome B y).event, f X ∂μ) = + ∫ X, f X ∂μ := by + simp_rw [← integral_indicator (withSyndrome B _).measurableSet_event] + rw [← integral_finsetSum _ (fun y _ => hf.indicator (withSyndrome B y).measurableSet_event)] + exact integral_congr_ae (Filter.Eventually.of_forall (sum_syndrome_indicators B f)) + +/-- Each actual new conditional law has the expected normalization factor. -/ +theorem integral_cond_syndrome {κ : Type*} [Finite κ] (old : κ → AffineBlock) + (B : AffineBlock) + (hold : Pairwise (fun i j => Disjoint (old i).support (old j).support)) + (hnew : ∀ k, Disjoint (old k).support B.support) + (y : Fin B.rank → ZMod 2) (f : Cantor → ℝ) : + (∫ X, f X ∂cond (finiteStageLaw old) (withSyndrome B y).event) = + (2 : ℝ) ^ B.rank * ∫ X in (withSyndrome B y).event, f X ∂finiteStageLaw old := by + rw [ProbabilityTheory.cond, integral_smul_measure, + finiteStageLaw_event_of_disjoint old (withSyndrome B y) hold hnew] + simp [ENNReal.toReal_inv, ENNReal.toReal_pow, smul_eq_mul] + +/-- Exact averaging over all syndromes recovers the old-stage expectation. -/ +theorem average_integral_cond_syndrome {κ : Type*} [Finite κ] (old : κ → AffineBlock) + (B : AffineBlock) + (hold : Pairwise (fun i j => Disjoint (old i).support (old j).support)) + (hnew : ∀ k, Disjoint (old k).support B.support) + {f : Cantor → ℝ} (hf : Integrable f (finiteStageLaw old)) : + (∑ y : Fin B.rank → ZMod 2, + ∫ X, f X ∂cond (finiteStageLaw old) (withSyndrome B y).event) / (2 : ℝ) ^ B.rank = + ∫ X, f X ∂finiteStageLaw old := by + simp_rw [integral_cond_syndrome old B hold hnew] + rw [← Finset.mul_sum, sum_setIntegral_syndromes B hf] + exact mul_div_cancel_left₀ _ (by positivity) + +/-- Some syndrome has objective no larger than the old expectation. The +computable minimizer attains at least this good a value. -/ +theorem exists_integral_cond_syndrome_le {κ : Type*} [Finite κ] (old : κ → AffineBlock) + (B : AffineBlock) + (hold : Pairwise (fun i j => Disjoint (old i).support (old j).support)) + (hnew : ∀ k, Disjoint (old k).support B.support) + {f : Cantor → ℝ} (hf : Integrable f (finiteStageLaw old)) : + ∃ y : Fin B.rank → ZMod 2, + (∫ X, f X ∂cond (finiteStageLaw old) (withSyndrome B y).event) ≤ + ∫ X, f X ∂finiteStageLaw old := by + classical + by_contra h + push Not at h + have hs := Finset.sum_lt_sum (s := (Finset.univ : Finset (Fin B.rank → ZMod 2))) + (fun y _ => (h y).le) ⟨0, Finset.mem_univ _, h 0⟩ + have ha := average_integral_cond_syndrome old B hold hnew hf + have hp : (0 : ℝ) < 2 ^ B.rank := by positivity + have hc : Fintype.card (Fin B.rank → ZMod 2) = 2 ^ B.rank := by simp + rw [Finset.sum_const, Finset.card_univ, hc, nsmul_eq_mul] at hs + have he := (div_eq_iff (ne_of_gt hp)).mp ha + push_cast at hs + nlinarith + +end Klr.StageSyndrome diff --git a/LeanPool/KLRandomness/StageSyndromeComputable.lean b/LeanPool/KLRandomness/StageSyndromeComputable.lean new file mode 100644 index 0000000000..f0808e543b --- /dev/null +++ b/LeanPool/KLRandomness/StageSyndromeComputable.lean @@ -0,0 +1,122 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.StageFiniteScan +import Mathlib.Tactic.Positivity + +/-! +# Computable exact minimization over the finite syndrome space + +The syndrome is recovered by finite search, not supplied as rank-many advice +bits. Ties retain the first minimizer in the explicit binary-word enumeration. +The computation is uniform in every parameter of the rational objective. +-/ + +@[expose] public section + +namespace Klr.StageSyndrome + +open SparseSearch RationalComputability + +/-- The first index minimizing a rational cost on `0, ..., n`. -/ +def minIndex (cost : ℕ → ℚ) : ℕ → ℕ + | 0 => 0 + | n + 1 => if cost (minIndex cost n) ≤ cost (n + 1) then minIndex cost n else n + 1 + +theorem minIndex_le (cost : ℕ → ℚ) (n : ℕ) : minIndex cost n ≤ n := by + induction n with + | zero => rfl + | succ n ih => simp only [minIndex]; split <;> omega + +theorem cost_minIndex_le (cost : ℕ → ℚ) (n k : ℕ) (hk : k ≤ n) : + cost (minIndex cost n) ≤ cost k := by + induction n with + | zero => + have : k = 0 := by omega + subst k + rfl + | succ n ih => + rw [minIndex] + split_ifs with h + · rcases Nat.eq_or_lt_of_le hk with rfl | hlt + · exact h + · exact ih (by omega) + · rcases Nat.eq_or_lt_of_le hk with rfl | hlt + · rfl + · exact (le_of_lt (lt_of_not_ge h)).trans (ih (by omega)) + +/-- Exact rational comparison makes the bounded minimization computable. -/ +theorem computable_minIndex {α : Type*} [Primcodable α] {cost : α → ℕ → ℚ} + (hc : Computable₂ cost) : + Computable (fun p : α × ℕ => minIndex (cost p.1) p.2) := by + have ha : Computable (fun p : (α × ℕ) × (ℕ × ℕ) => p.1.1) := + Computable.fst.comp Computable.fst + have hp : Computable (fun p : (α × ℕ) × (ℕ × ℕ) => p.2.2) := + Computable.snd.comp Computable.snd + have hn : Computable (fun p : (α × ℕ) × (ℕ × ℕ) => p.2.1 + 1) := + Primrec.succ.to_comp.comp (Computable.fst.comp Computable.snd) + have hle := primrec_rat_le.decide.to_comp.comp (hc.comp ha hp) (hc.comp ha hn) + have hs := Computable.cond hle hp hn + apply (Computable.nat_rec Computable.snd (Computable.const 0) hs.to₂).of_eq + intro p + induction p.2 with + | zero => rfl + | succ n ih => + simpa only [Nat.rec_add_one, Bool.cond_decide, minIndex] using + congrArg (fun k => if cost p.1 k ≤ cost p.1 (n + 1) then k else n + 1) ih + +/-- The finite syndrome minimizing the supplied exact rational objective. -/ +def choose (r : ℕ) (cost : List Bool → ℚ) : List Bool := + let ys := words r + ys.getD (minIndex (fun k => cost (ys.getD k [])) (ys.length - 1)) [] + +theorem choose_mem (r : ℕ) (cost : List Bool → ℚ) : choose r cost ∈ words r := by + have hpos : 0 < (words r).length := by rw [PoolAdvice.length_words]; positivity + have hk : minIndex (fun k => cost ((words r).getD k [])) ((words r).length - 1) < + (words r).length := lt_of_le_of_lt (minIndex_le _ _) (by omega) + unfold choose + rw [List.getD_eq_getElem _ [] hk] + exact List.getElem_mem _ + +@[simp] theorem length_choose (r : ℕ) (cost : List Bool → ℚ) : + (choose r cost).length = r := (mem_words_iff _ _).mp (choose_mem r cost) + +theorem choose_min (r : ℕ) (cost : List Bool → ℚ) (y : List Bool) (hy : y.length = r) : + cost (choose r cost) ≤ cost y := by + obtain ⟨k, hk, hky⟩ := List.getElem_of_mem ((mem_words_iff r y).mpr hy) + have h := cost_minIndex_le (fun k => cost ((words r).getD k [])) + ((words r).length - 1) k (by omega) + simpa only [choose, List.getD_eq_getElem _ [] hk, hky] using h + +/-- The chosen cost is at most the average over every possible syndrome. -/ +theorem choose_le_average (r : ℕ) (cost : List Bool → ℚ) : + cost (choose r cost) ≤ PoolAdvice.average r cost := by + have h := List.length_nsmul_le_sum ((words r).map cost) (cost (choose r cost)) (by + intro q hq + obtain ⟨y, hy, rfl⟩ := List.mem_map.mp hq + exact choose_min r cost y ((mem_words_iff _ _).mp hy)) + have hp : (0 : ℚ) < 2 ^ r := by positivity + apply (le_div_iff₀ hp).mpr + simpa [PoolAdvice.average, PoolAdvice.length_words, nsmul_eq_mul, mul_comm] using h + +/-- The minimizer is a total computation, even when the number of syndrome +bits and the entire rational objective vary with the reconstruction input. -/ +theorem computable_choose {α : Type*} [Primcodable α] {r : α → ℕ} + {cost : α → List Bool → ℚ} (hr : Computable r) (hc : Computable₂ cost) : + Computable (fun a => choose (r a) (cost a)) := by + have hy := computable_words.comp hr + have hg := (Primrec.list_getD []).to_comp.comp (hy.comp Computable.fst) Computable.snd + have hf := hc.comp Computable.fst hg + have hn := Primrec.nat_sub.to_comp.comp (Computable.list_length.comp hy) (Computable.const 1) + have hk := (computable_minIndex (cost := fun a k => cost a ((words (r a)).getD k [])) hf).comp + (Computable.id.pair hn) + exact (Primrec.list_getD []).to_comp.comp hy hk + +end Klr.StageSyndrome diff --git a/LeanPool/KLRandomness/StageSyndromeObjective.lean b/LeanPool/KLRandomness/StageSyndromeObjective.lean new file mode 100644 index 0000000000..b66cd7f4a1 --- /dev/null +++ b/LeanPool/KLRandomness/StageSyndromeObjective.lean @@ -0,0 +1,202 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.StageConditionalScan +public import LeanPool.KLRandomness.StageHorizonChoice +public import LeanPool.KLRandomness.StageRankCode + +/-! +# The actual computable finite syndrome objective + +This combines the executable support-wager and partial-rank tests with exact +finite conditional integration. For a fixed protected list of strategies, +the whole objective is uniformly computable in the pool, candidate, horizon, +and syndrome. Its values are the conditional integrals used in the analytic +syndrome-choice theorem. +-/ + +@[expose] public section + +noncomputable section + +namespace Klr.StageSyndromeObjective + +open MeasureTheory ProbabilityTheory SparseSearch SparseListSearch StageCandidate +open StageFiniteWager RationalComputability +open scoped BigOperators + +/-- Rational value of the finite objective on one answer transcript. -/ +def statistic (s : BettingStrategy) (G : List ℕ) (a : Entry) (v : List Bool) : ℚ := + truncatedCandidate s.normalize.scan (StageFiniteWager.normalizedWager s) G a v + + if StageRankCode.partialTest s.normalize.scan G a.2 v then 1 else 0 + +theorem computable_statistic (s : BettingStrategy) {α : Type*} [Primcodable α] + {G : α → List ℕ} {a : α → Entry} {v : α → List Bool} + (hG : Computable G) (ha : Computable a) (hv : Computable v) : + Computable (fun p => statistic s (G p) (a p) (v p)) := by + have ht := computable_normalized_truncatedCandidate s hG ha hv + have hp := StageRankCode.computable_partialTest s.normalize.scan hG + (Computable.snd.comp ha) hv + exact (primrec_rat_add.to_comp.comp ht + (Computable.cond hp (Computable.const (1 : ℚ)) (Computable.const 0))).of_eq + fun _ => by simp only [statistic, Bool.cond_eq_ite] + +/-- Actual conditional expectation of one strategy's finite objective. -/ +def oneCost (s : BettingStrategy) (cs : List AffineCode.Data) + (G : List ℕ) (a : Entry) (V : ℕ) (y : List Bool) : ℚ := + StageConditionalScan.expectation cs G a.2 y s.normalize.scan V (statistic s G a) + +theorem computable_oneCost (s : BettingStrategy) {α : Type*} [Primcodable α] + {cs : α → List AffineCode.Data} {G : α → List ℕ} {a : α → Entry} + {V : α → ℕ} {y : α → List Bool} + (hcs : Computable cs) (hG : Computable G) (ha : Computable a) + (hV : Computable V) (hy : Computable y) : + Computable (fun p => oneCost s (cs p) (G p) (a p) (V p) (y p)) := + StageConditionalScan.computable_expectation s.normalize.scan hcs hG + (Computable.snd.comp ha) hy hV + (computable_statistic s (hG.comp Computable.fst) (ha.comp Computable.fst) Computable.snd).to₂ + +/-- Sum the exact conditional costs over the fixed protected strategy list. -/ +def cost (rules : List BettingStrategy) (cs : List AffineCode.Data) + (G : List ℕ) (a : Entry) (V : ℕ) (y : List Bool) : ℚ := + (rules.map fun s => oneCost s cs G a V y).sum + +theorem computable_cost (rules : List BettingStrategy) {α : Type*} [Primcodable α] + {cs : α → List AffineCode.Data} {G : α → List ℕ} {a : α → Entry} + {V : α → ℕ} {y : α → List Bool} + (hcs : Computable cs) (hG : Computable G) (ha : Computable a) + (hV : Computable V) (hy : Computable y) : + Computable (fun p => cost rules (cs p) (G p) (a p) (V p) (y p)) := by + induction rules with + | nil => exact Computable.const 0 + | cons s rules ih => + exact primrec_rat_add.to_comp.comp (computable_oneCost s hcs hG ha hV hy) ih + +theorem statistic_transcript (s : BettingStrategy) (G : List ℕ) (hG : G.Nodup) + {m r : ℕ} (a : Entry) (ha : GoodEntry G.length m r a) + (z : Fin r → ZMod 2) (V : ℕ) (X : Cantor) : + (statistic s G a (s.normalize.scan.transcript X V) : ℝ) = + (truncated s.normalize.scan (StageFiniteWager.normalizedWager s) + (block G.get hG.injective_get a ha z).support (s.normalize.scan.transcript X V) : ℝ) + + (LateDropBound.partialEvent (block G.get hG.injective_get a ha z) + s.normalize.scan V).indicator (fun _ => (1 : ℝ)) X := by + rw [statistic, Rat.cast_add, truncatedCandidate_eq_block _ _ G hG a ha z] + congr 1 + have he := StageRankCode.partialTest_eq_true s.normalize.scan G hG a ha z + (s.normalize.scan.transcript X V) + change _ ↔ _ at he + by_cases hx : X ∈ LateDropBound.partialEvent (block G.get hG.injective_get a ha z) + s.normalize.scan V + · have ht := he.mpr hx + simp only [ht, ite_true, Rat.cast_one, Set.indicator_of_mem hx] + · have ht := mt he.mp hx + simp only [ht, Bool.false_eq_true, ite_false, Rat.cast_zero, Set.indicator_of_notMem hx] + +/-- The finite rational total is exactly the actual syndrome objective. -/ +theorem cost_eq_integral (rules : List BettingStrategy) (cs : List AffineCode.Data) + (G : List ℕ) (hG : G.Nodup) {m r : ℕ} + (a : Entry) (ha : GoodEntry G.length m r a) (V : ℕ) (y : List Bool) + (z : Fin r → ZMod 2) : + (cost rules cs G a V y : ℝ) = + ∫ X, StageHorizonChoice.objective (block G.get hG.injective_get a ha z) + (fun i : Fin rules.length => (rules.get i).normalize.scan) + (fun i : Fin rules.length => StageFiniteWager.normalizedWager (rules.get i)) V X + ∂cond (StageFiniteProbability.law cs) + (block G.get hG.injective_get a ha (wordVector r y)).event := by + let μ := cond (StageFiniteProbability.law cs) + (block G.get hG.injective_get a ha (wordVector r y)).event + have hs : (rules.map fun s => (oneCost s cs G a V y : ℝ)).sum = + ∑ i : Fin rules.length, (oneCost (rules.get i) cs G a V y : ℝ) := by + conv_lhs => rw [← List.ofFn_get rules, List.map_ofFn, List.sum_ofFn] + rfl + rw [cost, Rat.cast_list_sum, List.map_map] + change (rules.map fun s => (oneCost s cs G a V y : ℝ)).sum = _ + rw [hs] + simp only [StageHorizonChoice.objective] + rw [integral_finsetSum] + · apply Finset.sum_congr rfl + intro i _ + rw [oneCost, StageConditionalScan.expectation_eq_integral cs G hG a ha] + exact integral_congr_ae (Filter.Eventually.of_forall + (statistic_transcript (rules.get i) G hG a ha z V)) + · intro i _ + exact (StageHorizonChoice.integrable_truncated μ _ _ _ V + (StageFiniteWager.normalizedWager_abs_le_half (rules.get i))).add + ((integrable_const (1 : ℝ)).indicator (LateDropBound.measurableSet_partialEvent _ _ _)) + +/-- The chosen syndrome is a total finite computation, and is never advice. -/ +noncomputable def chosen (rules : List BettingStrategy) (cs : List AffineCode.Data) + (G : List ℕ) (a : Entry) (V : ℕ) : List Bool := + StageSyndrome.choose (AffineCode.rank a.2) (cost rules cs G a V) + +theorem computable_chosen (rules : List BettingStrategy) {α : Type*} [Primcodable α] + {cs : α → List AffineCode.Data} {G : α → List ℕ} {a : α → Entry} {V : α → ℕ} + (hcs : Computable cs) (hG : Computable G) (ha : Computable a) (hV : Computable V) : + Computable (fun p => chosen rules (cs p) (G p) (a p) (V p)) := + StageSyndrome.computable_choose (AffineCode.computable_rank.comp (Computable.snd.comp ha)) + (computable_cost rules (hcs.comp Computable.fst) (hG.comp Computable.fst) + (ha.comp Computable.fst) (hV.comp Computable.fst) Computable.snd).to₂ + +theorem chosen_min (rules : List BettingStrategy) (cs : List AffineCode.Data) + (G : List ℕ) (a : Entry) (V : ℕ) (y : List Bool) (hy : y.length = AffineCode.rank a.2) : + cost rules cs G a V (chosen rules cs G a V) ≤ cost rules cs G a V y := + StageSyndrome.choose_min _ _ y hy + +/-- The computed syndrome is an exact minimizer of the actual conditional +integral, with respect to every mathematical syndrome vector. -/ +theorem chosen_minimizes_integral (rules : List BettingStrategy) + (cs : List AffineCode.Data) (G : List ℕ) (hG : G.Nodup) {m r : ℕ} + (a : Entry) (ha : GoodEntry G.length m r a) (V : ℕ) : + ∀ z : Fin r → ZMod 2, + (∫ X, StageHorizonChoice.objective (block G.get hG.injective_get a ha 0) + (fun i : Fin rules.length => (rules.get i).normalize.scan) + (fun i : Fin rules.length => StageFiniteWager.normalizedWager (rules.get i)) V X + ∂cond (StageFiniteProbability.law cs) + (block G.get hG.injective_get a ha (wordVector r (chosen rules cs G a V))).event) ≤ + ∫ X, StageHorizonChoice.objective (block G.get hG.injective_get a ha 0) + (fun i : Fin rules.length => (rules.get i).normalize.scan) + (fun i : Fin rules.length => StageFiniteWager.normalizedWager (rules.get i)) V X + ∂cond (StageFiniteProbability.law cs) (block G.get hG.injective_get a ha z).event := by + intro z + let yz := List.ofFn (fun i : Fin r => FiniteMeasure.boolEquivF2.symm (z i)) + have hyz : yz.length = AffineCode.rank a.2 := by simp [yz, ha.2.2.2.1] + have hq := chosen_min rules cs G a V yz hyz + have hreal : (cost rules cs G a V (chosen rules cs G a V) : ℝ) ≤ + (cost rules cs G a V yz : ℝ) := by exact_mod_cast hq + rw [cost_eq_integral rules cs G hG a ha V (chosen rules cs G a V) 0, + cost_eq_integral rules cs G hG a ha V yz 0] at hreal + simpa only [yz, wordVector_ofFn] using hreal + +/-- Finish the stage from a reconstructed horizon, with no syndrome or +certificate supplied as additional input. -/ +noncomputable def finish (rules : List BettingStrategy) (cs : List AffineCode.Data) + (p : (List ℕ × Entry) × ℕ) : Part AffineCode.Data := + StageCandidateCode.reconstruct ((p.1.1, p.1.2.2), chosen rules cs p.1.1 p.1.2 p.2) + +theorem partrec_finish (rules : List BettingStrategy) (cs : List AffineCode.Data) : + Partrec (finish rules cs) := by + have hG : Computable (fun p : (List ℕ × Entry) × ℕ => p.1.1) := + Computable.fst.comp Computable.fst + have ha : Computable (fun p : (List ℕ × Entry) × ℕ => p.1.2) := + Computable.snd.comp Computable.fst + exact StageCandidateCode.partrec_reconstruct.comp + ((hG.pair (Computable.snd.comp ha)).pair + (computable_chosen rules (Computable.const cs) hG ha Computable.snd)) + +theorem finish_halts (rules : List BettingStrategy) (cs : List AffineCode.Data) + (G : List ℕ) (hG : G.Nodup) {m r : ℕ} + (a : Entry) (ha : GoodEntry G.length m r a) (V : ℕ) : + ∃ c ∈ finish rules cs ((G, a), V), + AffineCode.valid c = true ∧ AffineCode.rank c = r ∧ + AffineCode.event c = (block G.get hG.injective_get a ha + (wordVector r (chosen rules cs G a V))).event := + StageCandidateCode.exists_reconstructed_code G hG a ha (chosen rules cs G a V) + +end Klr.StageSyndromeObjective diff --git a/LeanPool/KLRandomness/StageWeights.lean b/LeanPool/KLRandomness/StageWeights.lean new file mode 100644 index 0000000000..19805a2a2b --- /dev/null +++ b/LeanPool/KLRandomness/StageWeights.lean @@ -0,0 +1,378 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.SparseListWeights +public import LeanPool.KLRandomness.EffectiveNormalizationStrategy +public import LeanPool.KLRandomness.DropEvents +public import LeanPool.KLRandomness.EarlyLateWagers +public import Mathlib.MeasureTheory.Constructions.Polish.Basic +public import Mathlib.MeasureTheory.Integral.Bochner.Basic +import Mathlib.Tactic.FieldSimp +import Mathlib.Tactic.Linarith +import Mathlib.Tactic.NormNum +import Mathlib.Tactic.Positivity +import Mathlib.Tactic.Ring + +/-! +# Actual all-time wager weights for a finite stage + +For a fresh scan, a position receives at most one wager along any input. +The all-time absolute wager on a finite support is therefore a finite sum, +even though the relevant query times need not have a uniform finite bound. +Its pathwise square budget gives the Cauchy--Schwarz bound used in Section 5. + +The incidence estimate for the actual executable sparse list then bounds the +average expected all-time support wager under any probability law. In +particular, the law may be the current finite affine stage law. +-/ + +@[expose] public section + +namespace Klr.StageWeights + +open MeasureTheory +open scoped BigOperators + +/-- The absolute wager charged to a position, zero if that position is never +queried on this input. Freshness makes the series have at most one nonzero term. -/ +noncomputable def wagerAt (π : ScanRule) (w : List Bool → ℝ) (a : ℕ) (X : Cantor) : ℝ := by + classical + exact ∑' t : ℕ, if π.query (π.transcript X t) = a then |w (π.transcript X t)| else 0 + +/-- The all-time absolute wager charged to a finite support. -/ +noncomputable def supportWager (π : ScanRule) (w : List Bool → ℝ) + (S : Finset ℕ) (X : Cantor) : ℝ := + ∑ a ∈ S, wagerAt π w a X + +theorem wagerAt_nonneg (π : ScanRule) (w : List Bool → ℝ) (a : ℕ) (X : Cantor) : + 0 ≤ wagerAt π w a X := by + classical + exact tsum_nonneg fun t => by split_ifs <;> positivity + +theorem supportWager_nonneg (π : ScanRule) (w : List Bool → ℝ) (S : Finset ℕ) (X : Cantor) : + 0 ≤ supportWager π w S X := + Finset.sum_nonneg fun a _ => wagerAt_nonneg π w a X + +theorem wagerAt_eq_of_query (π : ScanRule) (w : List Bool → ℝ) (X : Cantor) (t : ℕ) : + wagerAt π w (π.query (π.transcript X t)) X = |w (π.transcript X t)| := by + classical + rw [wagerAt, tsum_eq_single t] + · simp + · intro s hst + have hq : π.query (π.transcript X s) ≠ π.query (π.transcript X t) := + fun h => hst (π.query_injective X h) + simp [hq] + +theorem wagerAt_eq_zero_of_not_queried (π : ScanRule) (w : List Bool → ℝ) + (a : ℕ) (X : Cantor) (ha : ∀ t, π.query (π.transcript X t) ≠ a) : + wagerAt π w a X = 0 := by + classical + simp [wagerAt, ha] + +theorem measurable_wagerAt (π : ScanRule) (w : List Bool → ℝ) (a : ℕ) : + Measurable (wagerAt π w a) := by + classical + apply Measurable.tsum + intro t + exact DropEvents.measurable_transcript_eval π t + (fun v => if π.query v = a then |w v| else 0) + +theorem measurable_supportWager (π : ScanRule) (w : List Bool → ℝ) (S : Finset ℕ) : + Measurable (supportWager π w S) := + Finset.measurable_sum S fun a _ => measurable_wagerAt π w a + +/-- All query times in a fixed finite support form a finite set, by freshness. -/ +theorem finite_queryTimes (π : ScanRule) (S : Finset ℕ) (X : Cantor) : + {t : ℕ | π.query (π.transcript X t) ∈ S}.Finite := + S.finite_toSet.preimage (π.query_injective X).injOn + +/-- All query times at which a scan visits the given finite support on an input. -/ +noncomputable def queryTimes (π : ScanRule) (S : Finset ℕ) (X : Cantor) : Finset ℕ := + (finite_queryTimes π S X).toFinset + +@[simp] theorem mem_queryTimes (π : ScanRule) (S : Finset ℕ) (X : Cantor) (t : ℕ) : + t ∈ queryTimes π S X ↔ π.query (π.transcript X t) ∈ S := by + simp [queryTimes] + +/-- Reindexing by the actual fresh query times is exact, for any function that +vanishes at zero. Positions never queried contribute zero. -/ +theorem sum_wagerAt_comp_eq (π : ScanRule) (w : List Bool → ℝ) + (S : Finset ℕ) (X : Cantor) (f : ℝ → ℝ) (hf : f 0 = 0) : + (∑ a ∈ S, f (wagerAt π w a X)) = + ∑ t ∈ queryTimes π S X, f |w (π.transcript X t)| := by + classical + let q : ℕ → ℕ := fun t => π.query (π.transcript X t) + have hsub : (queryTimes π S X).image q ⊆ S := by + intro a ha + obtain ⟨t, ht, rfl⟩ := Finset.mem_image.mp ha + exact (mem_queryTimes π S X t).mp ht + calc + _ = ∑ a ∈ (queryTimes π S X).image q, f (wagerAt π w a X) := by + symm + apply Finset.sum_subset hsub + intro a ha hnot + have hn : ∀ t, q t ≠ a := by + intro t ht + exact hnot (Finset.mem_image.mpr ⟨t, + (mem_queryTimes π S X t).mpr (by change q t ∈ S; rw [ht]; exact ha), ht⟩) + rw [wagerAt_eq_zero_of_not_queried π w a X hn, hf] + _ = ∑ t ∈ queryTimes π S X, f (wagerAt π w (q t) X) := by + rw [Finset.sum_image] + intro i _ j _ hij + exact π.query_injective X hij + _ = _ := by + apply Finset.sum_congr rfl + intro t _ + rw [show q t = π.query (π.transcript X t) from rfl, wagerAt_eq_of_query] + +/-- The finite-position definition agrees with the paper's all-time sum over +queries into the support. -/ +theorem supportWager_eq_tsum (π : ScanRule) (w : List Bool → ℝ) + (S : Finset ℕ) (X : Cantor) : + supportWager π w S X = + ∑' t : ℕ, if π.query (π.transcript X t) ∈ S then |w (π.transcript X t)| else 0 := by + classical + change (∑ a ∈ S, id (wagerAt π w a X)) = _ + rw [sum_wagerAt_comp_eq π w S X id rfl] + rw [tsum_eq_sum (s := queryTimes π S X)] + · apply Finset.sum_congr rfl + intro t ht + simp [(mem_queryTimes π S X t).mp ht] + · intro t ht + simp only [mem_queryTimes] at ht + simp [ht] + +/-- Finite query horizons contribute no more than the complete support wager. -/ +theorem partial_supportWager_le (π : ScanRule) (w : List Bool → ℝ) + (S : Finset ℕ) (X : Cantor) (N : ℕ) : + (∑ t ∈ Finset.range N, + if π.query (π.transcript X t) ∈ S then |w (π.transcript X t)| else 0) ≤ + supportWager π w S X := by + classical + have hs : Summable (fun t : ℕ => + if π.query (π.transcript X t) ∈ S then |w (π.transcript X t)| else 0) := by + apply summable_of_ne_finset_zero (s := queryTimes π S X) + intro t ht + simp only [mem_queryTimes] at ht + simp [ht] + rw [supportWager_eq_tsum] + exact hs.sum_le_tsum _ (fun t _ => by split_ifs <;> positivity) + +/-- The actual early rank-drop wager total is dominated by the finite +support-wager sum through the same horizon. -/ +theorem earlyWager_le_partial_supportWager (B : ℕ → AffineBlock) (π : ScanRule) + (w : List Bool → ℝ) (V : ℕ → ℕ) (j : ℕ) (X : Cantor) : + EarlyLateWagers.earlyWager B π w V j X ≤ + ∑ t ∈ Finset.range (V j), + if π.query (π.transcript X t) ∈ (B j).support then |w (π.transcript X t)| else 0 := by + classical + unfold EarlyLateWagers.earlyWager + apply Finset.sum_le_sum + intro t ht + by_cases h : DropEvents.atTime B π j X t + · simp only [EarlyLateWagers.blockWager, h, ↓reduceIte, h.1, le_refl] + · simp only [EarlyLateWagers.blockWager, h, ↓reduceIte] + split_ifs <;> positivity + +/-- The actual early rank-drop wager total is dominated by the all-time +wager total on the block's support. -/ +theorem earlyWager_le_supportWager (B : ℕ → AffineBlock) (π : ScanRule) + (w : List Bool → ℝ) (V : ℕ → ℕ) (j : ℕ) (X : Cantor) : + EarlyLateWagers.earlyWager B π w V j X ≤ supportWager π w (B j).support X := + (earlyWager_le_partial_supportWager B π w V j X).trans + (partial_supportWager_le π w (B j).support X (V j)) + +/-- The square budget of the wagers at pool positions is bounded by the +actual square budget over all query times. -/ +theorem sum_wagerAt_sq_le (π : ScanRule) (w : List Bool → ℝ) + (S : Finset ℕ) (X : Cantor) + (hsum : Summable (fun t => (w (π.transcript X t)) ^ 2)) {C : ℝ} + (hC : (∑' t, (w (π.transcript X t)) ^ 2) ≤ C) : + (∑ a ∈ S, (wagerAt π w a X) ^ 2) ≤ C := by + rw [sum_wagerAt_comp_eq π w S X (fun x => x ^ 2) (by norm_num)] + simp_rw [sq_abs] + exact (hsum.sum_le_tsum _ (fun _ _ => sq_nonneg _)).trans hC + +/-- Cauchy--Schwarz for the actual all-time wagers on a finite support. -/ +theorem supportWager_le_sqrt (π : ScanRule) (w : List Bool → ℝ) + (S : Finset ℕ) (X : Cantor) + (hsum : Summable (fun t => (w (π.transcript X t)) ^ 2)) {C : ℝ} + (hC : (∑' t, (w (π.transcript X t)) ^ 2) ≤ C) : + supportWager π w S X ≤ Real.sqrt ((S.card : ℝ) * C) := by + classical + have hs := sum_wagerAt_sq_le π w S X hsum hC + have h := Sparse.sum_weights_le_sqrt (fun a : S => wagerAt π w a.val X) C + (fun a => wagerAt_nonneg π w a.val X) + (by rwa [Finset.sum_coe_sort S (fun a => (wagerAt π w a X) ^ 2)]) + rw [Finset.sum_coe_sort S (fun a => wagerAt π w a X)] at h + simpa only [supportWager, Fintype.card_coe] using h + +/-- Every finite-support total is integrable under every finite law, with a +uniform pathwise square budget. -/ +theorem integrable_supportWager (μ : Measure Cantor) [IsFiniteMeasure μ] + (π : ScanRule) (w : List Bool → ℝ) (S : Finset ℕ) {C : ℝ} + (hsum : ∀ X, Summable (fun t => (w (π.transcript X t)) ^ 2)) + (hC : ∀ X, (∑' t, (w (π.transcript X t)) ^ 2) ≤ C) : + Integrable (supportWager π w S) μ := by + apply Integrable.of_bound (measurable_supportWager π w S).aestronglyMeasurable + (Real.sqrt ((S.card : ℝ) * C)) + exact Filter.Eventually.of_forall fun X => by + rw [Real.norm_eq_abs, abs_of_nonneg (supportWager_nonneg π w S X)] + exact supportWager_le_sqrt π w S X (hsum X) (hC X) + +/-- Injectively labeling a finite pool preserves the support sum exactly. -/ +theorem supportWager_image {M : ℕ} (π : ScanRule) (w : List Bool → ℝ) + (e : Fin M → ℕ) (he : Function.Injective e) (S : Finset (Fin M)) (X : Cantor) : + supportWager π w (S.image e) X = ∑ i ∈ S, wagerAt π w (e i) X := by + classical + unfold supportWager + rw [Finset.sum_image] + exact fun i _ j _ h => he h + +/-- The all-time position weights on any injectively labeled pool obey the +same square budget as the original time-indexed wagers. -/ +theorem sum_wagerAt_sq_le_of_injective {M : ℕ} (π : ScanRule) (w : List Bool → ℝ) + (e : Fin M → ℕ) (he : Function.Injective e) (X : Cantor) + (hsum : Summable (fun t => (w (π.transcript X t)) ^ 2)) {C : ℝ} + (hC : (∑' t, (w (π.transcript X t)) ^ 2) ≤ C) : + (∑ i : Fin M, (wagerAt π w (e i) X) ^ 2) ≤ C := by + classical + have h := sum_wagerAt_sq_le π w (Finset.univ.image e) X hsum hC + rwa [Finset.sum_image (fun i _ j _ h => he h)] at h + +/-- The actual coded sparse-list incidence bound controls all-time support +wagers pathwise, before any probability law is chosen. -/ +theorem average_supportWager_le {M m r J : ℕ} {τ θ : ℚ} {L : SparseListSearch.CodeList} + (hL : SparseListSearch.Good M m r J τ θ L) (hJ : 0 < J) + (π : ScanRule) (w : List Bool → ℝ) (e : Fin M → ℕ) (he : Function.Injective e) + (X : Cantor) (hsum : Summable (fun t => (w (π.transcript X t)) ^ 2)) {C : ℝ} + (hC : (∑' t, (w (π.transcript X t)) ^ 2) ≤ C) : + (∑ j : Fin L.length, + supportWager π w ((SparseListWeights.support M (L.get j)).image e) X) / J ≤ + (2 * ((m : ℝ) / M)) * Real.sqrt ((M : ℝ) * C) := by + have h := SparseListWeights.average_supportWeight_le hL hJ + (fun i => wagerAt π w (e i) X) C (fun i => wagerAt_nonneg π w (e i) X) + (sum_wagerAt_sq_le_of_injective π w e he X hsum hC) + simpa only [supportWager_image π w e he, SparseListWeights.supportWeight] using h + +/-- Average expected all-time wager on the actual candidate supports, under +an arbitrary probability law such as the current finite-stage law. -/ +theorem average_integral_supportWager_le (μ : Measure Cantor) [IsProbabilityMeasure μ] + {M m r J : ℕ} {τ θ : ℚ} {L : SparseListSearch.CodeList} + (hL : SparseListSearch.Good M m r J τ θ L) (hJ : 0 < J) + (π : ScanRule) (w : List Bool → ℝ) (e : Fin M → ℕ) (he : Function.Injective e) + {C : ℝ} (hsum : ∀ X, Summable (fun t => (w (π.transcript X t)) ^ 2)) + (hC : ∀ X, (∑' t, (w (π.transcript X t)) ^ 2) ≤ C) : + (∑ j : Fin L.length, + ∫ X, supportWager π w ((SparseListWeights.support M (L.get j)).image e) X ∂μ) / J ≤ + (2 * ((m : ℝ) / M)) * Real.sqrt ((M : ℝ) * C) := by + let f (j : Fin L.length) := supportWager π w ((SparseListWeights.support M (L.get j)).image e) + have hf (j : Fin L.length) : Integrable (f j) μ := + integrable_supportWager μ π w _ hsum hC + calc + _ = ∫ X, (∑ j : Fin L.length, f j X) / J ∂μ := by + rw [integral_div, integral_finsetSum _ (fun j _ => hf j)] + _ ≤ ∫ _X : Cantor, + (2 * ((m : ℝ) / M)) * Real.sqrt ((M : ℝ) * C) ∂μ := by + apply integral_mono ((integrable_finsetSum _ (fun j _ => hf j)).div_const _) + (integrable_const _) + intro X + exact average_supportWager_le hL hJ π w e he X (hsum X) (hC X) + _ = _ := by simp + +/-- The averaging estimate sums over any finite protected family of scans. +It selects the same candidate family for all of them. -/ +theorem average_integral_family_supportWager_le {ι : Type*} [Fintype ι] + (μ : Measure Cantor) [IsProbabilityMeasure μ] + {M m r J : ℕ} {τ θ : ℚ} {L : SparseListSearch.CodeList} + (hL : SparseListSearch.Good M m r J τ θ L) (hJ : 0 < J) + (π : ι → ScanRule) (w : ι → List Bool → ℝ) + (e : Fin M → ℕ) (he : Function.Injective e) {C : ℝ} + (hsum : ∀ i X, Summable (fun t => (w i ((π i).transcript X t)) ^ 2)) + (hC : ∀ i X, (∑' t, (w i ((π i).transcript X t)) ^ 2) ≤ C) : + (∑ j : Fin L.length, ∑ i : ι, + ∫ X, supportWager (π i) (w i) ((SparseListWeights.support M (L.get j)).image e) X ∂μ) / J ≤ + (Fintype.card ι : ℝ) * ((2 * ((m : ℝ) / M)) * Real.sqrt ((M : ℝ) * C)) := by + rw [Finset.sum_comm, Finset.sum_div] + calc + _ ≤ ∑ _i : ι, (2 * ((m : ℝ) / M)) * Real.sqrt ((M : ℝ) * C) := + Finset.sum_le_sum fun i _ => + average_integral_supportWager_le μ hL hJ (π i) (w i) e he (hsum i) (hC i) + _ = _ := by simp + +/-- The actual normalized strategies discharge the pathwise square-budget +hypotheses of the simultaneous expectation estimate. -/ +theorem average_integral_normalized_supportWager_le {ι : Type*} [Fintype ι] + (μ : Measure Cantor) [IsProbabilityMeasure μ] + {M m r J : ℕ} {τ θ : ℚ} {L : SparseListSearch.CodeList} + (hL : SparseListSearch.Good M m r J τ θ L) (hJ : 0 < J) + (s : ι → BettingStrategy) (e : Fin M → ℕ) (he : Function.Injective e) : + (∑ j : Fin L.length, ∑ i : ι, + ∫ X, supportWager (s i).normalize.scan (s i).normalize.capital.wager + ((SparseListWeights.support M (L.get j)).image e) X ∂μ) / J ≤ + (Fintype.card ι : ℝ) * ((2 * ((m : ℝ) / M)) * Real.sqrt ((M : ℝ) / 2)) := by + simpa only [mul_one_div] using average_integral_family_supportWager_le μ hL hJ + (fun i => (s i).normalize.scan) (fun i => (s i).normalize.capital.wager) e he + (fun i X => (s i).normalize_wagers_summable X) + (fun i X => (s i).normalize_wagers_tsum_le_half X) + +/-- The paper's polynomial choices give the exact inverse-square bound. -/ +theorem polynomial_supportWager_bound_eq (r : ℕ) : + (2 * ((SparseParameters.supportSize r : ℝ) / SparseParameters.blockSize r)) * + Real.sqrt ((SparseParameters.blockSize r : ℝ) / 2) = + Real.sqrt 2 / (r : ℝ) ^ 2 := by + simp only [SparseParameters.supportSize, SparseParameters.blockSize, Nat.cast_pow] + rw [Real.sqrt_div (by positivity), + show (r : ℝ) ^ 8 = ((r : ℝ) ^ 4) ^ 2 by ring, + Real.sqrt_sq (by positivity)] + by_cases hr : r = 0 + · simp [hr] + · have hr' : (r : ℝ) ≠ 0 := by exact_mod_cast hr + have hs : Real.sqrt 2 ≠ 0 := ne_of_gt (Real.sqrt_pos.mpr (by norm_num)) + have hs2 : (2 : ℝ) / Real.sqrt 2 = Real.sqrt 2 := by + apply (div_eq_iff hs).mpr + nlinarith [Real.sq_sqrt (by norm_num : (0 : ℝ) ≤ 2)] + calc + _ = (2 / Real.sqrt 2) * (1 / (r : ℝ) ^ 2) := by field_simp + _ = _ := by rw [hs2]; ring + +/-- The checked executable construction has the paper's simultaneous +inverse-square expected-wager estimate for every protected finite family. -/ +theorem average_integral_normalized_supportWager_le_of_construct + {ι : Type*} [Fintype ι] (μ : Measure Cantor) [IsProbabilityMeasure μ] + {τ θ : ℚ} {r : ℕ} {L : SparseListSearch.CodeList} + (hL : L ∈ SparseListConstruction.construct τ θ r) (hr : 0 < r) + (s : ι → BettingStrategy) (e : Fin (SparseParameters.blockSize r) → ℕ) + (he : Function.Injective e) : + (∑ j : Fin L.length, ∑ i : ι, + ∫ X, supportWager (s i).normalize.scan (s i).normalize.capital.wager + ((SparseListWeights.support (SparseParameters.blockSize r) (L.get j)).image e) X ∂μ) / + SparseParameters.listSize r ≤ + (Fintype.card ι : ℝ) * (Real.sqrt 2 / (r : ℝ) ^ 2) := by + have hJ : 0 < SparseParameters.listSize r := by + unfold SparseParameters.listSize SparseParameters.blockSize + positivity + simpa only [polynomial_supportWager_bound_eq] using + average_integral_normalized_supportWager_le μ + (SparseListConstruction.construct_spec hL) hJ s e he + +/-- The simultaneous support-wager allowance can be made smaller than any +positive stage error by increasing the trial rank. -/ +theorem eventually_family_supportWager_bound_lt (n : ℕ) {ε : ℝ} (hε : 0 < ε) : + ∀ᶠ r : ℕ in Filter.atTop, + (n : ℝ) * (Real.sqrt 2 / (r : ℝ) ^ 2) < ε := by + have h : Filter.Tendsto (fun r : ℕ => (n : ℝ) * (Real.sqrt 2 / (r : ℝ) ^ 2)) + Filter.atTop (nhds 0) := by + have ht := (SparseParameters.tendsto_nat_power 2 (by decide)).inv_tendsto_atTop + simpa [div_eq_mul_inv, Nat.cast_pow] using + (ht.const_mul (Real.sqrt 2)).const_mul (n : ℝ) + exact h.eventually_lt_const hε + +end Klr.StageWeights diff --git a/LeanPool/KLRandomness/StoppingTranscript.lean b/LeanPool/KLRandomness/StoppingTranscript.lean new file mode 100644 index 0000000000..3a3dc1eb4c --- /dev/null +++ b/LeanPool/KLRandomness/StoppingTranscript.lean @@ -0,0 +1,366 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.AffineFamily +import Mathlib.Tactic.NormNum + +/-! +# Countable unions of first-trigger transcripts + +A prefix-free family of finite transcripts specifies disjoint input events. +Consequently an equality or a constant affine-syndrome factor on each member +passes to the countable union. This is the measure-theoretic step needed when +a proof stops immediately before a first rank drop at an unbounded time. + +The trigger is a predicate of the transcript already observed. For a pre-drop +stopping event it describes the next query, before its answer is revealed. +-/ + +@[expose] public section + +namespace Klr.StoppingTranscript + +open MeasureTheory ProbabilityTheory +open scoped ENNReal + +/-- The input event producing one prescribed finite transcript. -/ +def inputEvent (π : ScanRule) (v : List Bool) : Set Cantor := + {X | π.transcript X v.length = v} + +/-- No two distinct members of a prefix-free family extend one another. -/ +def PrefixFree (W : Set (List Bool)) : Prop := + ∀ ⦃u v⦄, u ∈ W → v ∈ W → u <+: v → u = v + +/-- The countable union of the input events indexed by a transcript family. -/ +def unionEvent (π : ScanRule) (W : Set (List Bool)) : Set Cantor := + ⋃ v : W, inputEvent π v.val + +theorem measurableSet_inputEvent (π : ScanRule) (v : List Bool) : + MeasurableSet (inputEvent π v) := π.measurableSet_transcript v + +theorem measurableSet_unionEvent (π : ScanRule) (W : Set (List Bool)) : + MeasurableSet (unionEvent π W) := + MeasurableSet.iUnion fun v => measurableSet_inputEvent π v.val + +theorem PrefixFree.mono {W V : Set (List Bool)} (hW : PrefixFree W) (hVW : V ⊆ W) : + PrefixFree V := fun _ _ hu hv huv => hW (hVW hu) (hVW hv) huv + +/-- Two transcripts observed on the same input must be comparable by the prefix relation. -/ +theorem comparable_of_mem_inputEvent (π : ScanRule) {u v : List Bool} {X : Cantor} + (hu : X ∈ inputEvent π u) (hv : X ∈ inputEvent π v) : u <+: v ∨ v <+: u := by + change π.transcript X u.length = u at hu + change π.transcript X v.length = v at hv + rcases le_total u.length v.length with h | h + · exact Or.inl (by simpa only [hu, hv] using π.transcript_prefix X h) + · exact Or.inr (by simpa only [hu, hv] using π.transcript_prefix X h) + +/-- Prefix-free transcript families determine pairwise disjoint input events. -/ +theorem pairwiseDisjoint_inputEvent (π : ScanRule) {W : Set (List Bool)} + (hW : PrefixFree W) : Pairwise (fun u v : W => Disjoint (inputEvent π u.val) + (inputEvent π v.val)) := by + intro u v huv + apply Set.disjoint_left.mpr + intro X hu hv + rcases comparable_of_mem_inputEvent π hu hv with h | h + · exact huv (Subtype.ext (hW u.property v.property h)) + · exact huv (Subtype.ext (hW v.property u.property h).symm) + +/-- Exact countable additivity over a prefix-free transcript family. -/ +theorem measure_unionEvent (μ : Measure Cantor) (π : ScanRule) + {W : Set (List Bool)} (hW : PrefixFree W) : + μ (unionEvent π W) = ∑' v : W, μ (inputEvent π v.val) := + measure_iUnion (pairwiseDisjoint_inputEvent π hW) + (fun v => measurableSet_inputEvent π v.val) + +/-- Equality of transcript probabilities transfers to their prefix-free countable union. -/ +theorem measure_unionEvent_eq (μ ν : Measure Cantor) (π : ScanRule) + {W : Set (List Bool)} (hW : PrefixFree W) + (h : ∀ v ∈ W, μ (inputEvent π v) = ν (inputEvent π v)) : + μ (unionEvent π W) = ν (unionEvent π W) := by + rw [measure_unionEvent μ π hW, measure_unionEvent ν π hW] + exact tsum_congr fun v => h v.val v.property + +/-- A fixed syndrome factor transfers from individual stopping transcripts to their union. -/ +theorem measure_unionEvent_inter (μ : Measure Cantor) (π : ScanRule) + {W : Set (List Bool)} (hW : PrefixFree W) {E : Set Cantor} + (hE : MeasurableSet E) (p : ℝ≥0∞) + (h : ∀ v ∈ W, μ (inputEvent π v ∩ E) = p * μ (inputEvent π v)) : + μ (unionEvent π W ∩ E) = p * μ (unionEvent π W) := by + rw [unionEvent, Set.iUnion_inter] + have hd : Pairwise (fun u v : W => Disjoint (inputEvent π u.val ∩ E) + (inputEvent π v.val ∩ E)) := by + intro u v huv + exact (pairwiseDisjoint_inputEvent π hW huv).mono + Set.inter_subset_left Set.inter_subset_left + rw [measure_iUnion hd (fun v => (measurableSet_inputEvent π v.val).inter hE)] + simp_rw [h _ (Subtype.property _)] + rw [ENNReal.tsum_mul_left] + congr 1 + exact (measure_unionEvent μ π hW).symm + +/-- Conditioning on a syndrome preserves the law of a prefix-free stopping union when +its cylinder factors agree with the syndrome's nonzero finite probability. -/ +theorem cond_unionEvent (μ : Measure Cantor) (π : ScanRule) + {W : Set (List Bool)} (hW : PrefixFree W) {E : Set Cantor} + (hE : MeasurableSet E) (p : ℝ≥0∞) (hprob : μ E = p) + (hp0 : p ≠ 0) (hpTop : p ≠ ∞) + (h : ∀ v ∈ W, μ (inputEvent π v ∩ E) = p * μ (inputEvent π v)) : + (cond μ E) (unionEvent π W) = μ (unionEvent π W) := by + rw [cond_apply hE, Set.inter_comm, measure_unionEvent_inter μ π hW hE p h, + hprob, ← mul_assoc, ENNReal.inv_mul_cancel hp0 hpTop, one_mul] + +/-- The first place where a predicate of the currently observed transcript triggers. -/ +def firstTrigger (B : List Bool → Prop) : Set (List Bool) := + {v | B v ∧ ∀ n < v.length, ¬B (v.take n)} + +/-- First-trigger transcripts are prefix-free, without any monotonicity assumption on `B`. -/ +theorem firstTrigger_prefixFree (B : List Bool → Prop) : PrefixFree (firstTrigger B) := by + intro u v hu hv huv + by_contra hne + have hlen : u.length < v.length := by + have hle := huv.length_le + have hn : u.length ≠ v.length := fun h => hne (huv.eq_of_length h) + omega + have hn := hv.2 u.length hlen + rw [← List.prefix_iff_eq_take.mp huv] at hn + exact hn hu.1 + +/-- The union of first-trigger cylinders is exactly the event that a trigger ever occurs. -/ +theorem mem_unionEvent_firstTrigger_iff (π : ScanRule) (B : List Bool → Prop) (X : Cantor) : + X ∈ unionEvent π (firstTrigger B) ↔ ∃ n, B (π.transcript X n) := by + classical + constructor + · intro h + obtain ⟨v, hv⟩ := Set.mem_iUnion.mp h + exact ⟨v.val.length, hv.symm ▸ v.property.1⟩ + · intro h + let n := Nat.find h + have hv : π.transcript X n ∈ firstTrigger B := by + constructor + · exact Nat.find_spec h + · intro k hk + rw [π.transcript_take X (by simpa using hk.le)] + exact Nat.find_min h (by simpa [n] using hk) + apply Set.mem_iUnion.mpr + refine ⟨⟨π.transcript X n, hv⟩, ?_⟩ + change π.transcript X (π.transcript X n).length = π.transcript X n + simp + +/-- First-trigger cylinders restricted to times at or beyond a fixed horizon. Query +numbering in the paper is one greater than transcript length. -/ +def firstTriggerTail (B : List Bool → Prop) (N : ℕ) : Set (List Bool) := + {v | v ∈ firstTrigger B ∧ N ≤ v.length} + +theorem firstTriggerTail_prefixFree (B : List Bool → Prop) (N : ℕ) : + PrefixFree (firstTriggerTail B N) := + (firstTrigger_prefixFree B).mono (fun _ h => h.1) + +/-- A tail union records the first trigger, not an arbitrary later trigger. -/ +theorem mem_unionEvent_firstTriggerTail_iff (π : ScanRule) (B : List Bool → Prop) + (N : ℕ) (X : Cantor) : + X ∈ unionEvent π (firstTriggerTail B N) ↔ + ∃ n, N ≤ n ∧ B (π.transcript X n) ∧ ∀ k < n, ¬B (π.transcript X k) := by + constructor + · intro h + obtain ⟨v, hv⟩ := Set.mem_iUnion.mp h + refine ⟨v.val.length, v.property.2, hv.symm ▸ v.property.1.1, ?_⟩ + intro k hk + have hn := v.property.1.2 k hk + rw [← hv, π.transcript_take X hk.le] at hn + exact hn + · rintro ⟨n, hN, hB, hfirst⟩ + have hv : π.transcript X n ∈ firstTriggerTail B N := by + constructor + · constructor + · exact hB + · intro k hk + rw [π.transcript_take X (by simpa using hk.le)] + exact hfirst k (by simpa using hk) + · simpa using hN + apply Set.mem_iUnion.mpr + refine ⟨⟨π.transcript X n, hv⟩, ?_⟩ + change π.transcript X (π.transcript X n).length = π.transcript X n + simp + +/-- The next queried position is chosen before its bit is revealed, so the set of +positions read after that query is independent of the answer. -/ +theorem queriedPositions_append_singleton_eq (π : ScanRule) (v : List Bool) (b c : Bool) : + π.queriedPositions (v ++ [b]) = π.queriedPositions (v ++ [c]) := by + have hsub (a d : Bool) : π.queriedPositions (v ++ [a]) ⊆ + π.queriedPositions (v ++ [d]) := by + intro q hq + obtain ⟨i, _, hi⟩ := Finset.mem_image.mp hq + have hi0 : i.val ≤ v.length := by + have ht := i.isLt + simp only [List.length_append, List.length_singleton] at ht + omega + let j : Fin (v ++ [d]).length := ⟨i.val, by simpa using i.isLt⟩ + refine Finset.mem_image.mpr ⟨j, Finset.mem_univ _, ?_⟩ + change π.query ((v ++ [d]).take i.val) = q + simpa only [List.take_append_of_le_length hi0] using hi + exact Finset.Subset.antisymm (hsub b c) (hsub c b) + +/-- Whether the next query destroys full unread rank is independent of the next answer. -/ +theorem unreadFullRank_append_singleton_iff (B : AffineBlock) (π : ScanRule) + (v : List Bool) (b c : Bool) : + B.UnreadFullRank π (v ++ [b]) ↔ B.UnreadFullRank π (v ++ [c]) := by + have hO : B.observed π (v ++ [b]) = B.observed π (v ++ [c]) := by + simp only [AffineBlock.observed, queriedPositions_append_singleton_eq π v b c] + have aux (O T : Set B.support) (dO : DecidablePred (· ∈ O)) + (dT : DecidablePred (· ∈ T)) (h : O = T) : + Function.Surjective (@AffineObservation.unreadMap _ _ B.matrix O dO) ↔ + Function.Surjective (@AffineObservation.unreadMap _ _ B.matrix T dT) := by + subst T + cases Subsingleton.elim dO dT + rfl + exact aux _ _ _ _ hO + +/-- A predictable trigger for the first drop from full row rank. The test using `false` +is valid for either answer by `unreadFullRank_append_singleton_iff`. -/ +def rankDropTrigger (B : AffineBlock) (π : ScanRule) (v : List Bool) : Prop := + B.UnreadFullRank π v ∧ ¬B.UnreadFullRank π (v ++ [false]) + +theorem rankDropTrigger_transcript_iff (B : AffineBlock) (π : ScanRule) + (X : Cantor) (n : ℕ) : + rankDropTrigger B π (π.transcript X n) ↔ + B.UnreadFullRank π (π.transcript X n) ∧ + ¬B.UnreadFullRank π (π.transcript X (n + 1)) := by + rw [ScanRule.transcript_succ] + exact and_congr Iff.rfl (not_congr (unreadFullRank_append_singleton_iff B π + (π.transcript X n) false (X (π.query (π.transcript X n))))) + +/-- The first loss of full unread rank occurs after at least `N` answers have been +observed. The event is recorded immediately before the rank-destroying query. -/ +def rankDropTailEvent (B : AffineBlock) (π : ScanRule) (N : ℕ) : Set Cantor := + {X | ∃ n, N ≤ n ∧ + (∀ k ≤ n, B.UnreadFullRank π (π.transcript X k)) ∧ + ¬B.UnreadFullRank π (π.transcript X (n + 1))} + +/-- The predictable first-trigger union is exactly the first-rank-drop tail event. -/ +theorem unionEvent_rankDropTriggerTail (B : AffineBlock) (π : ScanRule) (N : ℕ) : + unionEvent π (firstTriggerTail (rankDropTrigger B π) N) = + rankDropTailEvent B π N := by + classical + ext X + rw [mem_unionEvent_firstTriggerTail_iff] + constructor + · rintro ⟨n, hN, hdrop, hfirst⟩ + obtain ⟨_, hfail⟩ := (rankDropTrigger_transcript_iff B π X n).mp hdrop + refine ⟨n, hN, ?_, hfail⟩ + intro k hk + induction k with + | zero => simpa using B.unreadFullRank_nil π + | succ k ih => + have hkn : k < n := by omega + have hprev := ih (by omega) + by_contra hbad + exact hfirst k hkn ((rankDropTrigger_transcript_iff B π X k).mpr ⟨hprev, hbad⟩) + · rintro ⟨n, hN, hfull, hfail⟩ + refine ⟨n, hN, (rankDropTrigger_transcript_iff B π X n).mpr + ⟨hfull n le_rfl, hfail⟩, ?_⟩ + intro k hk hdrop + exact ((rankDropTrigger_transcript_iff B π X k).mp hdrop).2 + (hfull (k + 1) (by omega)) + +/-- The exact affine stage factor passes to an unbounded prefix-free stopping family. -/ +theorem finiteStage_unionEvent_inter {κ : Type*} [Finite κ] + (old : κ → AffineBlock) (B : AffineBlock) + (hdis : ∀ k, Disjoint (old k).support B.support) (π : ScanRule) + {W : Set (List Bool)} (hW : PrefixFree W) + (hfull : ∀ v ∈ W, B.UnreadFullRank π v) : + (AffineBlock.finiteStageLaw old) (unionEvent π W ∩ B.event) = + (1 / 2 : ℝ≥0∞) ^ B.rank * (AffineBlock.finiteStageLaw old) (unionEvent π W) := by + apply measure_unionEvent_inter (AffineBlock.finiteStageLaw old) π hW + B.measurableSet_event ((1 / 2 : ℝ≥0∞) ^ B.rank) + intro v hv + exact AffineBlock.finiteStage_identity old B hdis π v (hfull v hv) + +/-- Once the syndrome's mass is known, conditioning preserves every such stopping event. -/ +theorem finiteStage_cond_unionEvent {κ : Type*} [Finite κ] + (old : κ → AffineBlock) (B : AffineBlock) + (hdis : ∀ k, Disjoint (old k).support B.support) (π : ScanRule) + {W : Set (List Bool)} (hW : PrefixFree W) + (hfull : ∀ v ∈ W, B.UnreadFullRank π v) + (hprob : (AffineBlock.finiteStageLaw old) B.event = (1 / 2 : ℝ≥0∞) ^ B.rank) : + (cond (AffineBlock.finiteStageLaw old) B.event) (unionEvent π W) = + (AffineBlock.finiteStageLaw old) (unionEvent π W) := by + apply cond_unionEvent (AffineBlock.finiteStageLaw old) π hW B.measurableSet_event + ((1 / 2 : ℝ≥0∞) ^ B.rank) hprob + · exact pow_ne_zero _ (by norm_num) + · finiteness + · intro v hv + exact AffineBlock.finiteStage_identity old B hdis π v (hfull v hv) + +/-- For an actual nonnull old block family, the new syndrome has the needed mass. -/ +theorem finiteStage_cond_unionEvent_of_nonnull {κ : Type*} [Finite κ] + (old : κ → AffineBlock) (B : AffineBlock) + (hdis : ∀ k, Disjoint (old k).support B.support) (π : ScanRule) + {W : Set (List Bool)} (hW : PrefixFree W) + (hfull : ∀ v ∈ W, B.UnreadFullRank π v) + (hold : fairCoin (AffineBlock.familyEvent old) ≠ 0) : + (cond (AffineBlock.finiteStageLaw old) B.event) (unionEvent π W) = + (AffineBlock.finiteStageLaw old) (unionEvent π W) := + finiteStage_cond_unionEvent old B hdis π hW hfull + (AffineBlock.finiteStageLaw_event old B hdis hold) + +/-- The two finite-stage laws agree on the stopping union: conditioning directly on all +old constraints and the new syndrome gives the same result as the old stage alone. -/ +theorem finiteStage_unionEvent_preserved {κ : Type*} [Finite κ] + (old : κ → AffineBlock) (B : AffineBlock) + (hdis : ∀ k, Disjoint (old k).support B.support) (π : ScanRule) + {W : Set (List Bool)} (hW : PrefixFree W) + (hfull : ∀ v ∈ W, B.UnreadFullRank π v) + (hold : fairCoin (AffineBlock.familyEvent old) ≠ 0) : + (cond fairCoin (AffineBlock.familyEvent old ∩ B.event)) (unionEvent π W) = + (AffineBlock.finiteStageLaw old) (unionEvent π W) := by + rw [← cond_cond_eq_cond_inter (AffineBlock.measurableSet_familyEvent old) + B.measurableSet_event fairCoin] + exact finiteStage_cond_unionEvent_of_nonnull old B hdis π hW hfull hold + +/-- The stage laws agree on the first-rank-drop tail, with no bound on the stopping time. -/ +theorem finiteStage_rankDropTail_preserved {κ : Type*} [Finite κ] + (old : κ → AffineBlock) (B : AffineBlock) + (hdis : ∀ k, Disjoint (old k).support B.support) (π : ScanRule) (N : ℕ) + (hold : fairCoin (AffineBlock.familyEvent old) ≠ 0) : + (cond fairCoin (AffineBlock.familyEvent old ∩ B.event)) + (unionEvent π (firstTriggerTail (rankDropTrigger B π) N)) = + (AffineBlock.finiteStageLaw old) + (unionEvent π (firstTriggerTail (rankDropTrigger B π) N)) := by + apply finiteStage_unionEvent_preserved old B hdis π + (firstTriggerTail_prefixFree (rankDropTrigger B π) N) _ hold + intro v hv + exact hv.1.1.1 + +/-- For pairwise disjoint old blocks, the stopping-union transfer needs no separate +assumption that the old constraint event has nonzero measure. -/ +theorem nextStage_unionEvent {κ : Type*} [Finite κ] + (old : κ → AffineBlock) (B : AffineBlock) + (hold : Pairwise (fun i j => Disjoint (old i).support (old j).support)) + (hnew : ∀ k, Disjoint (old k).support B.support) (π : ScanRule) + {W : Set (List Bool)} (hW : PrefixFree W) + (hfull : ∀ v ∈ W, B.UnreadFullRank π v) : + (cond fairCoin (AffineBlock.familyEvent old ∩ B.event)) (unionEvent π W) = + (AffineBlock.finiteStageLaw old) (unionEvent π W) := + finiteStage_unionEvent_preserved old B hnew π hW hfull + (AffineBlock.fairCoin_familyEvent_ne_zero old hold) + +/-- Adding a disjoint full-rank block preserves the distribution of its own first +rank-drop tail, including unbounded stopping times. -/ +theorem nextStage_rankDropTail {κ : Type*} [Finite κ] + (old : κ → AffineBlock) (B : AffineBlock) + (hold : Pairwise (fun i j => Disjoint (old i).support (old j).support)) + (hnew : ∀ k, Disjoint (old k).support B.support) (π : ScanRule) (N : ℕ) : + (cond fairCoin (AffineBlock.familyEvent old ∩ B.event)) (rankDropTailEvent B π N) = + (AffineBlock.finiteStageLaw old) (rankDropTailEvent B π N) := by + rw [← unionEvent_rankDropTriggerTail] + exact finiteStage_rankDropTail_preserved old B hnew π N + (AffineBlock.fairCoin_familyEvent_ne_zero old hold) + +end Klr.StoppingTranscript diff --git a/LeanPool/KLRandomness/StrategyCountability.lean b/LeanPool/KLRandomness/StrategyCountability.lean new file mode 100644 index 0000000000..c30c3493c3 --- /dev/null +++ b/LeanPool/KLRandomness/StrategyCountability.lean @@ -0,0 +1,135 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.ComputableRational +public import LeanPool.KLRandomness.EffectiveNormalizationStrategy +public import LeanPool.KLRandomness.ScanMeasure +public import Mathlib.Analysis.SpecificLimits.Basic +public import Mathlib.Computability.PartrecCode +import Mathlib.Tactic.NormNum +import Mathlib.Tactic.Ring + +/-! +# Countably many total computable-real betting strategies + +The construction may enumerate total strategies non-effectively. Countability +does not supply a computable enumeration of the total programs. We prove it +by choosing a computable rational approximation for each real capital function; +two capitals with the same approximation are equal. + +The final almost-everywhere quantifier interchange uses this actual countable +strategy type, rather than assuming that a chosen program list covers it. +-/ + +@[expose] public section + +namespace Klr + +open MeasureTheory Filter +open scoped Topology + +/-- Computable functions between any two primitively encodable types form a countable type. -/ +theorem countable_computable_functions {α β : Type*} [Primcodable α] [Primcodable β] : + Countable {f : α → β // Computable f} := by + classical + let code : {f : α → β // Computable f} → Nat.Partrec.Code := + fun f => (Nat.Partrec.Code.exists_code.mp f.property).choose + apply Function.Injective.countable (f := code) + intro f g h + apply Subtype.ext + funext a + have hf := congrFun (Nat.Partrec.Code.exists_code.mp f.property).choose_spec + (Encodable.encode a) + have hg := congrFun (Nat.Partrec.Code.exists_code.mp g.property).choose_spec + (Encodable.encode a) + change (code f).eval (Encodable.encode a) = _ at hf + change (code g).eval (Encodable.encode a) = _ at hg + rw [← h] at hg + simpa using hf.symm.trans hg + +/-- A uniformly vanishing rational error bound determines the real capital uniquely. -/ +theorem capital_eq_of_common_approximation {d e : List Bool → ℝ} + (q : List Bool → ℕ → ℚ) + (hd : ∀ v n, |(q v n : ℝ) - d v| ≤ (1 / 2 : ℝ) ^ n) + (he : ∀ v n, |(q v n : ℝ) - e v| ≤ (1 / 2 : ℝ) ^ n) : d = e := by + funext v + have hle (n : ℕ) : |d v - e v| ≤ 2 * (1 / 2 : ℝ) ^ n := by + calc + |d v - e v| = |(d v - (q v n : ℝ)) + ((q v n : ℝ) - e v)| := by ring_nf + _ ≤ |d v - (q v n : ℝ)| + |(q v n : ℝ) - e v| := abs_add_le _ _ + _ ≤ (1 / 2 : ℝ) ^ n + (1 / 2 : ℝ) ^ n := + add_le_add (by simpa only [abs_sub_comm] using hd v n) (he v n) + _ = _ := by ring + have hlim : Tendsto (fun n : ℕ => 2 * (1 / 2 : ℝ) ^ n) atTop (𝓝 0) := by + simpa using (tendsto_pow_atTop_nhds_zero_of_lt_one + (by norm_num : (0 : ℝ) ≤ 1 / 2) (by norm_num : (1 / 2 : ℝ) < 1)).const_mul 2 + exact sub_eq_zero.mp (abs_eq_zero.mp + (le_antisymm (ge_of_tendsto hlim (Eventually.of_forall hle)) (abs_nonneg _))) + +theorem ScanRule.ext_query {π τ : ScanRule} (h : π.query = τ.query) : π = τ := by + cases π + cases τ + cases h + rfl + +theorem CapitalProcess.ext_value {d e : CapitalProcess} (h : d.value = e.value) : d = e := by + cases d + cases e + cases h + rfl + +/-- The total strategies are countable, including their uniformly computable real capital. -/ +instance : Countable BettingStrategy := by + classical + have := countable_computable_functions (α := List Bool) (β := ℕ) + have := countable_computable_functions (α := List Bool × ℕ) (β := ℚ) + let data : BettingStrategy → + {f : List Bool → ℕ // Computable f} × + {q : List Bool × ℕ → ℚ // Computable q} := fun s => + (⟨s.scan.query, s.scan.computable_query⟩, + ⟨fun p => s.computable_capital.choose p.1 p.2, + RationalComputability.computable_rat_of_numDen s.computable_capital.choose_spec.1⟩) + apply Function.Injective.countable (f := data) + intro s t h + have hscan : s.scan = t.scan := + ScanRule.ext_query (congrArg (fun p => p.1.val) h) + have hq : (fun p : List Bool × ℕ => s.computable_capital.choose p.1 p.2) = + (fun p : List Bool × ℕ => t.computable_capital.choose p.1 p.2) := + congrArg (fun p => p.2.val) h + have hvalue : s.capital.value = t.capital.value := by + apply capital_eq_of_common_approximation s.computable_capital.choose + s.computable_capital.choose_spec.2 + intro v n + rw [show s.computable_capital.choose v n = t.computable_capital.choose v n from + congrFun hq (v, n)] + exact t.computable_capital.choose_spec.2 v n + have hcapital : s.capital = t.capital := CapitalProcess.ext_value hvalue + cases s + cases t + cases hscan + cases hcapital + rfl + +/-- A separate null success set for each total strategy suffices simultaneously for all of them. -/ +theorem ae_kolmogorovLovelandRandom_iff (μ : Measure Cantor) : + (∀ᵐ X ∂μ, KolmogorovLovelandRandom X) ↔ + ∀ s : BettingStrategy, ∀ᵐ X ∂μ, ¬s.Succeeds X := + ae_all_iff + +/-- It suffices to defeat all the normalized strategies almost surely. -/ +theorem ae_kolmogorovLovelandRandom_of_normalized (μ : Measure Cantor) + (h : ∀ s : BettingStrategy, ∀ᵐ X ∂μ, ¬s.normalize.Succeeds X) : + ∀ᵐ X ∂μ, KolmogorovLovelandRandom X := by + apply (ae_kolmogorovLovelandRandom_iff μ).mpr + intro s + filter_upwards [h s] with X hX + exact fun hs => hX (s.normalize_preserves_success hs) + +end Klr diff --git a/LeanPool/KLRandomness/UniformSupport.lean b/LeanPool/KLRandomness/UniformSupport.lean new file mode 100644 index 0000000000..8a200b5f6f --- /dev/null +++ b/LeanPool/KLRandomness/UniformSupport.lean @@ -0,0 +1,194 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import LeanPool.KLRandomness.UniformSupportCount +public import LeanPool.KLRandomness.FiniteProbability +import Mathlib.Tactic.FieldSimp +import Mathlib.Tactic.Linarith +import Mathlib.Tactic.NormNum +import Mathlib.Tactic.Positivity +import Mathlib.Tactic.Ring + +/-! +# Intersection moments of an actual uniform fixed-size support + +The one- and two-coordinate inclusion counts yield the mean and a variance +bound for intersection with any unread set. A finite Markov argument then +gives the support tail estimate used by Lemma 4. All averages are over the +actual finite type `Support M m`, not supplied moment hypotheses. +-/ + +@[expose] public section + +namespace Klr.UniformSupport + +open FiniteProbability +open scoped BigOperators + +variable {M m : ℕ} + +/-- The indicator that the sampled support contains a fixed pool position. -/ +def inclusion (a : Fin M) (S : Support M m) : ℝ := if a ∈ S.val then 1 else 0 + +theorem probability_contains_one (hm1 : 1 ≤ m) (hmM : m ≤ M) (a : Fin M) : + probability {S : Support M m | a ∈ S.val} = (m : ℝ) / M := by + rw [probability_eq_card, card_contains_one hm1, card_support] + exact choose_ratio_one hm1 hmM + +theorem average_inclusion (hm1 : 1 ≤ m) (hmM : m ≤ M) (a : Fin M) : + average (inclusion (m := m) a) = (m : ℝ) / M := by + calc + average (inclusion (m := m) a) = probability {S : Support M m | a ∈ S.val} := by + unfold probability + apply average_congr + intro S + by_cases h : a ∈ S.val <;> simp [inclusion, h] + _ = _ := probability_contains_one hm1 hmM a + +theorem probability_contains_pair (hm2 : 2 ≤ m) (hmM : m ≤ M) + (a b : Fin M) (hab : a ≠ b) : + probability {S : Support M m | a ∈ S.val ∧ b ∈ S.val} = + ((m : ℝ) * (m - 1)) / ((M : ℝ) * (M - 1)) := by + rw [probability_eq_card, card_contains_pair hm2 a b hab, card_support] + exact choose_ratio_pair hm2 hmM + +theorem average_inclusion_mul_le (hm2 : 2 ≤ m) (hmM : m ≤ M) (a b : Fin M) : + average (fun S : Support M m => inclusion a S * inclusion b S) ≤ + ((m : ℝ) / M) ^ 2 + if a = b then (m : ℝ) / M else 0 := by + by_cases hab : a = b + · subst b + have he : (fun S : Support M m => inclusion a S * inclusion a S) = inclusion a := by + funext S + simp [inclusion] + rw [he, average_inclusion (by omega) hmM] + simp only [ite_true] + nlinarith [sq_nonneg ((m : ℝ) / M)] + · have he : average (fun S : Support M m => inclusion a S * inclusion b S) = + probability {S : Support M m | a ∈ S.val ∧ b ∈ S.val} := by + unfold probability + apply average_congr + intro S + by_cases ha : a ∈ S.val <;> by_cases hb : b ∈ S.val <;> simp [inclusion, ha, hb] + rw [he, probability_eq_card, card_contains_pair hm2 a b hab, card_support] + simpa only [ite_eq_right hab, add_zero] using choose_ratio_pair_le_sq hm2 hmM + +/-- The size of the sampled support's intersection with the fixed unread set. -/ +def intersectionSize (D : Finset (Fin M)) (S : Support M m) : ℝ := (S.val ∩ D).card + +theorem intersectionSize_nonneg (D : Finset (Fin M)) (S : Support M m) : + 0 ≤ intersectionSize D S := Nat.cast_nonneg _ + +theorem intersectionSize_eq_sum (D : Finset (Fin M)) (S : Support M m) : + intersectionSize D S = ∑ a : D, inclusion a.val S := by + rw [Finset.sum_coe_sort D (fun a => inclusion a S)] + unfold intersectionSize + simp only [inclusion, ← Finset.sum_filter, Finset.sum_const, nsmul_eq_mul, mul_one] + congr 2 + ext a + simp [and_comm] + +/-- The exact mean intersection size `m*|D|/M`. -/ +noncomputable def mean (D : Finset (Fin M)) (m : ℕ) : ℝ := (m : ℝ) * D.card / M + +theorem average_intersectionSize (hm1 : 1 ≤ m) (hmM : m ≤ M) (D : Finset (Fin M)) : + average (intersectionSize (m := m) D) = mean D m := by + change average (fun S : Support M m => intersectionSize D S) = _ + simp_rw [intersectionSize_eq_sum] + rw [average_sum] + simp only [average_inclusion hm1 hmM, Finset.sum_const, Finset.card_univ, + Fintype.card_coe, nsmul_eq_mul] + unfold mean + ring + +/-- A sufficient second-moment estimate, derived from negative pair correlations. -/ +theorem average_intersectionSize_sq_le (hm2 : 2 ≤ m) (hmM : m ≤ M) + (D : Finset (Fin M)) : + average (fun S : Support M m => (intersectionSize D S) ^ 2) ≤ mean D m ^ 2 + mean D m := by + have he (S : Support M m) : (intersectionSize D S)^2 = + ∑ a : D, ∑ b : D, inclusion a.val S * inclusion b.val S := by + rw [intersectionSize_eq_sum, pow_two, Finset.sum_mul_sum] + simp_rw [he] + rw [average_sum] + simp_rw [average_sum] + calc + _ ≤ ∑ a : D, ∑ b : D, + (((m : ℝ) / M)^2 + if a.val = b.val then (m : ℝ) / M else 0) := by + apply Finset.sum_le_sum + intro a _ + exact Finset.sum_le_sum fun b _ => average_inclusion_mul_le hm2 hmM a.val b.val + _ = mean D m ^ 2 + mean D m := by + have hinner (a : D) : + (∑ b : D, (((m : ℝ) / M)^2 + if a.val = b.val then (m : ℝ) / M else 0)) = + (D.card : ℝ) * ((m : ℝ) / M)^2 + (m : ℝ) / M := by + simp only [Finset.sum_add_distrib, Finset.sum_const, Finset.card_univ, + Fintype.card_coe, nsmul_eq_mul, Subtype.val_inj] + simp + simp_rw [hinner] + simp only [Finset.sum_const, Finset.card_univ, Fintype.card_coe, nsmul_eq_mul] + unfold mean + ring + +/-- The variance of sampling without replacement is at most the mean. -/ +theorem variance_le_mean (hm2 : 2 ≤ m) (hmM : m ≤ M) (D : Finset (Fin M)) : + average (fun S : Support M m => (intersectionSize D S - mean D m)^2) ≤ mean D m := by + have : Nonempty (Support M m) := support_nonempty hmM + have he : (fun S : Support M m => (intersectionSize D S - mean D m)^2) = + fun S => (intersectionSize D S)^2 - (2 * mean D m) * intersectionSize D S + mean D m^2 := by + funext S + ring + rw [he, average_add, average_sub, average_const_mul, average_const, + average_intersectionSize (by omega) hmM] + have hs := average_intersectionSize_sq_le hm2 hmM D + nlinarith + +/-- Chebyshev's bound for an intersection smaller than `2r`, when its mean is at least `4r`. -/ +theorem probability_small_intersection_le (hm2 : 2 ≤ m) (hmM : m ≤ M) + (D : Finset (Fin M)) (r : ℕ) (hmean : 0 < mean D m) + (hr : 4 * (r : ℝ) ≤ mean D m) : + probability {S : Support M m | (S.val ∩ D).card < 2 * r} ≤ 4 / mean D m := by + have : Nonempty (Support M m) := support_nonempty hmM + have hhalf : 0 < (mean D m / 2)^2 := sq_pos_of_pos (by positivity) + have hsub : {S : Support M m | (S.val ∩ D).card < 2 * r} ⊆ + {S | (mean D m / 2)^2 ≤ (intersectionSize D S - mean D m)^2} := by + intro S hS + change (S.val ∩ D).card < 2 * r at hS + change (mean D m / 2)^2 ≤ (intersectionSize D S - mean D m)^2 + have hS' : intersectionSize D S < 2 * (r : ℝ) := by + unfold intersectionSize + exact_mod_cast hS + have hneg : intersectionSize D S - mean D m ≤ -(mean D m / 2) := by linarith + have hN := intersectionSize_nonneg D S + nlinarith + calc + _ ≤ probability {S : Support M m | + (mean D m / 2)^2 ≤ (intersectionSize D S - mean D m)^2} := probability_mono hsub + _ ≤ average (fun S : Support M m => (intersectionSize D S - mean D m)^2) / + (mean D m / 2)^2 := + probability_le_average_div _ (fun _ => sq_nonneg _) _ hhalf + _ ≤ mean D m / (mean D m / 2)^2 := + div_le_div_of_nonneg_right (variance_le_mean hm2 hmM D) hhalf.le + _ = 4 / mean D m := by field_simp; ring + +/-- A dense unread set gives the uniform support tail bound used in Lemma 4. -/ +theorem probability_small_intersection_le_density (hm2 : 2 ≤ m) (hmM : m ≤ M) + (D : Finset (Fin M)) (r : ℕ) (τ : ℝ) (hτ : 0 < τ) + (hD : τ * M ≤ (D.card : ℝ)) (hr : 4 * (r : ℝ) ≤ τ * m) : + probability {S : Support M m | (S.val ∩ D).card < 2 * r} ≤ 4 / (τ * m) := by + have hM : (0 : ℝ) < M := by exact_mod_cast (by omega : 0 < M) + have hm : (0 : ℝ) < m := by exact_mod_cast (by omega : 0 < m) + have hmean : τ * m ≤ mean D m := by + unfold mean + apply (le_div_iff₀ hM).mpr + nlinarith [mul_le_mul_of_nonneg_left hD hm.le] + have hpos : 0 < τ * (m : ℝ) := mul_pos hτ hm + exact (probability_small_intersection_le hm2 hmM D r (hpos.trans_le hmean) + (hr.trans hmean)).trans (div_le_div_of_nonneg_left (by norm_num) hpos hmean) + +end Klr.UniformSupport diff --git a/LeanPool/KLRandomness/UniformSupportCount.lean b/LeanPool/KLRandomness/UniformSupportCount.lean new file mode 100644 index 0000000000..9d523ae9f5 --- /dev/null +++ b/LeanPool/KLRandomness/UniformSupportCount.lean @@ -0,0 +1,132 @@ +/- +Copyright (c) 2026 Bjørn Kjos-Hanssen. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Bjørn Kjos-Hanssen +-/ + +-- Modified for Lean Pool. + +module + +public import Mathlib.SetTheory.Cardinal.Finite +public import Mathlib.Basic.Real.Basic +public import Mathlib.Data.Fintype.Powerset +public import Mathlib.Data.Finset.Powerset +public import Mathlib.Data.Fintype.Card +public import Mathlib.Data.Nat.Choose.Basic +import Mathlib.Tactic.FieldSimp +import Mathlib.Tactic.Linarith + +/-! +# Counts for uniformly chosen fixed-size supports + +The sample space is the actual finite type of `m`-element subsets of a pool +of `M` positions. Counts for containing a fixed set specialize to the one- +and two-position inclusion probabilities needed for the support variance bound. +-/ + +@[expose] public section + +namespace Klr.UniformSupport + +/-- The finite sample space of supports with exactly `m` positions. -/ +abbrev Support (M m : ℕ) := {S : Finset (Fin M) // S.card = m} + +theorem card_support (M m : ℕ) : Fintype.card (Support M m) = M.choose m := by + rw [Fintype.card_subtype] + have he : (Finset.univ.filter (fun S : Finset (Fin M) => S.card = m)) = + (Finset.univ : Finset (Fin M)).powersetCard m := by + ext S + simp + rw [he, Finset.card_powersetCard] + simp + +theorem card_support_pos {M m : ℕ} (hm : m ≤ M) : 0 < Fintype.card (Support M m) := by + rw [card_support] + exact Nat.choose_pos hm + +theorem support_nonempty {M m : ℕ} (hm : m ≤ M) : Nonempty (Support M m) := + Fintype.card_pos_iff.mp (card_support_pos hm) + +private def eventEquiv (M m : ℕ) (P : Finset (Fin M) → Prop) [DecidablePred P] : + {S : Support M m // P S.val} ≃ + ↥(((Finset.univ : Finset (Fin M)).powersetCard m).filter P) where + toFun S := ⟨S.val.val, by simpa using And.intro S.val.property S.property⟩ + invFun S := ⟨⟨S.val, by simpa using (Finset.mem_filter.mp S.property).1⟩, + (Finset.mem_filter.mp S.property).2⟩ + left_inv S := rfl + right_inv S := rfl + +theorem card_event (M m : ℕ) (P : Finset (Fin M) → Prop) [DecidablePred P] : + Nat.card {S : Support M m | P S.val} = + (((Finset.univ : Finset (Fin M)).powersetCard m).filter P).card := by + change Nat.card {S : Support M m // P S.val} = _ + rw [Nat.card_congr (eventEquiv M m P), Nat.card_eq_fintype_card, Fintype.card_coe] + +/-- Exact number of supports containing a prescribed finite set. -/ +theorem card_contains {M m : ℕ} (T : Finset (Fin M)) (hTm : T.card ≤ m) : + Nat.card {S : Support M m | T ⊆ S.val} = (M - T.card).choose (m - T.card) := by + rw [card_event] + simpa using Finset.card_filter_powersetCard_subset T Finset.univ m + (Finset.subset_univ _) hTm + +theorem card_contains_one {M m : ℕ} (hm : 1 ≤ m) (a : Fin M) : + Nat.card {S : Support M m | a ∈ S.val} = (M - 1).choose (m - 1) := by + simpa using card_contains (m := m) ({a} : Finset (Fin M)) (by simpa using hm) + +theorem card_contains_pair {M m : ℕ} (hm : 2 ≤ m) (a b : Fin M) (hab : a ≠ b) : + Nat.card {S : Support M m | a ∈ S.val ∧ b ∈ S.val} = + (M - 2).choose (m - 2) := by + simpa [hab, Finset.insert_subset_iff] using + card_contains (m := m) ({a, b} : Finset (Fin M)) (by simp [hab, hm]) + +theorem choose_ratio_one {M m : ℕ} (hm1 : 1 ≤ m) (hmM : m ≤ M) : + ((M - 1).choose (m - 1) : ℝ) / M.choose m = (m : ℝ) / M := by + have hM : 0 < M := by omega + have hC : (M.choose m : ℝ) ≠ 0 := by exact_mod_cast (Nat.choose_pos hmM).ne' + have hM' : (M : ℝ) ≠ 0 := by exact_mod_cast hM.ne' + apply (div_eq_div_iff hC hM').mpr + have h := Nat.add_one_mul_choose_eq (M - 1) (m - 1) + have he : M * (M - 1).choose (m - 1) = M.choose m * m := by + simpa only [Nat.sub_add_cancel hM, Nat.sub_add_cancel hm1] using h + exact_mod_cast (by nlinarith [he] : (M - 1).choose (m - 1) * M = m * M.choose m) + +theorem choose_ratio_pair {M m : ℕ} (hm2 : 2 ≤ m) (hmM : m ≤ M) : + ((M - 2).choose (m - 2) : ℝ) / M.choose m = + ((m : ℝ) * (m - 1)) / ((M : ℝ) * (M - 1)) := by + have hM2 : 2 ≤ M := by omega + have hC : (M.choose m : ℝ) ≠ 0 := by exact_mod_cast (Nat.choose_pos hmM).ne' + have hM : (M : ℝ) ≠ 0 := by exact_mod_cast (by omega : M ≠ 0) + have hM1 : (M : ℝ) - 1 ≠ 0 := by + have hh : (2 : ℝ) ≤ M := by exact_mod_cast hM2 + linarith + apply (div_eq_div_iff hC (mul_ne_zero hM hM1)).mpr + have h1 : M * (M - 1).choose (m - 1) = M.choose m * m := by + simpa only [Nat.sub_add_cancel (by omega : 1 ≤ M), Nat.sub_add_cancel (by omega : 1 ≤ m)] + using Nat.add_one_mul_choose_eq (M - 1) (m - 1) + have h2 : (M - 1) * (M - 2).choose (m - 2) = + (M - 1).choose (m - 1) * (m - 1) := by + simpa only [show M - 2 + 1 = M - 1 by omega, show m - 2 + 1 = m - 1 by omega] + using Nat.add_one_mul_choose_eq (M - 2) (m - 2) + have he : (M - 2).choose (m - 2) * (M * (M - 1)) = + (m * (m - 1)) * M.choose m := by nlinarith [congrArg (M * ·) h2] + have he' := congrArg (fun n : ℕ => (n : ℝ)) he + push_cast at he' + simpa only [Nat.cast_sub (by omega : 1 ≤ M), Nat.cast_sub (by omega : 1 ≤ m), + Nat.cast_one] using he' + +/-- Sampling without replacement makes two distinct inclusion indicators negatively correlated. -/ +theorem choose_ratio_pair_le_sq {M m : ℕ} (hm2 : 2 ≤ m) (hmM : m ≤ M) : + ((M - 2).choose (m - 2) : ℝ) / M.choose m ≤ ((m : ℝ) / M) ^ 2 := by + rw [choose_ratio_pair hm2 hmM] + have hM : (0 : ℝ) < M := by exact_mod_cast (by omega : 0 < M) + have hM1 : (0 : ℝ) < M - 1 := by + have hh : (2 : ℝ) ≤ M := by exact_mod_cast (le_trans hm2 hmM) + linarith + have hm : (0 : ℝ) ≤ m := Nat.cast_nonneg m + have hmM' : (m : ℝ) ≤ M := by exact_mod_cast hmM + apply (div_le_iff₀ (mul_pos hM hM1)).mpr + field_simp + nlinarith + +end Klr.UniformSupport diff --git a/LeanPool/projects/kl-randomness.yaml b/LeanPool/projects/kl-randomness.yaml new file mode 100644 index 0000000000..2bdf4c09ff --- /dev/null +++ b/LeanPool/projects/kl-randomness.yaml @@ -0,0 +1,58 @@ +slug: kl-randomness +title: Kolmogorov–Loveland and Martin–Löf randomness +summary: >- + Formalizes the separation of Martin–Löf randomness from Kolmogorov–Loveland + randomness for binary sequences under Liu and Meng's convention of total + fresh scans and uniformly computable real capital. It also proves that + randomness for base-four strategies need not imply binary + Kolmogorov–Loveland randomness under adjacent-bit grouping. The proof + develops effective open tests, methods for conditioning on parity + constraints, and success-preserving transformations of betting strategies. +branch: computability theory +entry_module: LeanPool.KLRandomness +authors: +- Bjørn Kjos-Hanssen +source: + title: Separating Kolmogorov–Loveland randomness from Martin–Löf randomness + arxiv: 2611.31004v1 + url: https://github.com/bjoernkjoshanssen/klr/tree/81f5fef2de3142aad714624033a5aa4f12031a6b + github_repo: bjoernkjoshanssen/klr + commit: 81f5fef2de3142aad714624033a5aa4f12031a6b + announcement_url: https://palomar-registry.org/entry.html?id=PALOMAR-2026-11-26-000060&version=1 + announcement_date: '2026-11-26' +license: Apache-2.0 +status: verified +provenance: AI +provenance_evidence: >- + The upstream formalization manifest credits Bjørn Kjos-Hanssen with + research direction, mathematical feedback and maintenance, and AI agents + with writing and revising the Lean proofs. +main_declarations: +- Klr.martinLofRandom_ssubset_kolmogorovLovelandRandom +- Klr.exists_not_martinLofRandom_no_partial_rational_success +- Klr.binary_random_ssubset_baseFour_random +main_results: +- declaration: Klr.martinLofRandom_ssubset_kolmogorovLovelandRandom + informal: >- + The binary sequences avoiding all Martin–Löf tests form a proper subset + of those on which every total fresh computable betting strategy with + nonnegative fair and uniformly computable real capital has bounded capital. +- declaration: Klr.exists_not_martinLofRandom_no_partial_rational_success + informal: >- + Some binary sequence fails a Martin–Löf test while every infinite fresh + run of a partial rational-wager program on that sequence has bounded capital. +- declaration: Klr.binary_random_ssubset_baseFour_random + informal: >- + The binary Kolmogorov–Loveland random sequences form a proper subset of + the sequences whose adjacent-bit pairs are Kolmogorov–Loveland random + digits in base four, with total computable-real strategies in both bases. + This is an additional upstream result from pull request 3, separate + from the result registered with Palomar. +tags: +- algorithmic randomness +- computability +- martingales +- effective measure theory +msc: +- '03D32' +- '03B35'