import Mathlib namespace OAI namespace CommonBasesFPRAS section abbrev IndependenceOracle (n : ℕ) := Bool → (Fin n → Bool) → Bool def ExactOracles {n : ℕ} (M₁ M₂ : Matroid (Fin n)) (O : IndependenceOracle n) : Prop := ∀ (which : Bool) (A : Fin n → Bool), O which A = true ↔ (if which then M₂ else M₁).Indep {i | A i = true} noncomputable def commonBaseCount {n : ℕ} (M₁ M₂ : Matroid (Fin n)) : ℕ := Nat.card {A : Finset (Fin n) // M₁.IsBase (A : Set (Fin n)) ∧ M₂.IsBase (A : Set (Fin n))} inductive Instruction (k s : ℕ) where | push (register : Fin (k + 8)) (bit : Bool) (next : Fin (s + 1)) | pop (register : Fin (k + 8)) (empty zero one : Fin (s + 1)) | coin (zero one : Fin (s + 1)) | query (which : Bool) (register : Fin (k + 8)) (no yes : Fin (s + 1)) | halt def Program (k s : ℕ) := Fin (s + 1) → Instruction k s def binaryValue : List Bool → ℕ | [] => 0 | b :: l => (if b then 1 else 0) + 2 * binaryValue l structure MachineConfig (k s : ℕ) where registers : Fin (k + 8) → List Bool control : Fin (s + 1) output : Option ℚ := none oracleCalls : ℕ := 0 bitOperations : ℕ := 0 def inputLength (n r : ℕ) (ε δ : ℚ) : ℕ := 6 + n.bits.length + r.bits.length + ε.num.natAbs.bits.length + ε.den.bits.length + δ.num.natAbs.bits.length + δ.den.bits.length def initialConfig (k s n r : ℕ) (ε δ : ℚ) : MachineConfig k s where registers := fun i => match i.val with | 0 => n.bits | 1 => r.bits | 2 => ε.num.natAbs.bits | 3 => ε.den.bits | 4 => δ.num.natAbs.bits | 5 => δ.den.bits | _ => [] control := 0 def machineStep {k s n : ℕ} (P : Program k s) (O : IndependenceOracle n) (randomBit : Bool) (c : MachineConfig k s) : MachineConfig k s := if c.output.isSome then c else match P c.control with | .push i b next => { c with registers := Function.update c.registers i (b :: c.registers i) control := next bitOperations := c.bitOperations + 1 } | .pop i empty zero one => match c.registers i with | [] => { c with control := empty bitOperations := c.bitOperations + 1 } | b :: l => { c with registers := Function.update c.registers i l control := if b then one else zero bitOperations := c.bitOperations + 1 } | .coin zero one => { c with control := if randomBit then one else zero bitOperations := c.bitOperations + 1 } | .query which i no yes => if (c.registers i).length = n then { c with control := if O which (fun j => (c.registers i)[j.val]?.getD false) then yes else no oracleCalls := c.oracleCalls + 1 bitOperations := c.bitOperations + (c.registers i).length + n + 1 } else { c with output := some 0 bitOperations := c.bitOperations + (c.registers i).length + n + 1 } | .halt => { c with output := some ((binaryValue (c.registers ⟨6, by omega⟩) : ℚ) / (binaryValue (c.registers ⟨7, by omega⟩) : ℚ)) bitOperations := c.bitOperations + (c.registers ⟨6, by omega⟩).length + (c.registers ⟨7, by omega⟩).length + 1 } def execution {k s n : ℕ} (P : Program k s) (O : IndependenceOracle n) (c : MachineConfig k s) (bits : ℕ → Bool) : ℕ → MachineConfig k s | 0 => c | t + 1 => machineStep P O (bits t) (execution P O c bits t) def finiteBits {B : ℕ} (bits : Fin B → Bool) (t : ℕ) : Bool := if h : t < B then bits ⟨t, h⟩ else false def relativeAccuracy (ε : ℚ) (Z : ℕ) (z : ℚ) : Prop := (1-ε)*(Z:ℚ)≤z ∧ z≤(1+ε)*(Z:ℚ) def resourceBound (C d n r : ℕ) (ε δ : ℚ) : ℕ := C * (1 + n + inputLength n r ε δ + ⌈ε⁻¹⌉₊ + Nat.clog 2 ⌈δ⁻¹⌉₊) ^ d def MainTheorem : Prop := ∃ (k s : ℕ) (P : Program k s) (C d : ℕ), 0 < C ∧ ∀ (n r : ℕ) (M₁ M₂ : Matroid (Fin n)) (O : IndependenceOracle n) (ε δ : ℚ), M₁.E = Set.univ → M₂.E = Set.univ → M₁.eRank = (r : ℕ∞) → M₂.eRank = (r : ℕ∞) → ExactOracles M₁ M₂ O → 0 < ε → ε < 1 → 0 < δ → δ < 1 → let B := resourceBound C d n r ε δ let Z := commonBaseCount M₁ M₂ (∀ bits : ℕ → Bool, let out := execution P O (initialConfig k s n r ε δ) bits B out.output.isSome ∧ out.oracleCalls ≤ B ∧ out.bitOperations ≤ B ∧ ∀ z, out.output = some z → 0 ≤ z ∧ (Z = 0 → z = 0)) ∧ (1 - δ) * (2 : ℚ) ^ B ≤ (Nat.card {bits : Fin B → Bool // ∃ z, (execution P O (initialConfig k s n r ε δ) (finiteBits bits) B).output = some z ∧ relativeAccuracy ε Z z} : ℚ) section open scoped RealInnerProductSpace BigOperators Matrix variable {V : Type*} [AddCommGroup V] [Module ℝ V] def OnePositive (B : LinearMap.BilinForm ℝ V) : Prop := ∀ e, 0 < B e e → ∀ v, B v e = 0 → B v v ≤ 0 theorem onePositive_of_nonpositive_kernel (B : LinearMap.BilinForm ℝ V) (hsymm : B.IsSymm) (L : V →ₗ[ℝ] ℝ) (hker : ∀ v, L v = 0 → B v v ≤ 0) : OnePositive B := by intro e he v hve by_contra hv have hvpos : 0 < B v v := lt_of_not_ge hv have hLe : L e ≠ 0 := by intro h exact (not_le_of_gt he) (hker e h) have hev : B e v = 0 := by rw [hsymm.eq e v, hve] have hz : L ((L e) • v - (L v) • e) = 0 := by simp only [map_sub, map_smul, smul_eq_mul] ring have hq := hker ((L e) • v - (L v) • e) hz simp only [map_sub, map_smul, LinearMap.sub_apply, LinearMap.smul_apply, smul_eq_mul, hve, hev, mul_zero, sub_zero] at hq have hLe2 : 0 < (L e)^2 := sq_pos_of_ne_zero hLe have hn : 0 ≤ (L v)^2 * B e e := mul_nonneg (sq_nonneg _) (le_of_lt he) have hp : 0 < (L e)^2 * B v v := mul_pos hLe2 hvpos nlinarith section Spectral variable {E : Type*} [NormedAddCommGroup E] [InnerProductSpace ℝ E] [FiniteDimensional ℝ E] theorem spectral_kernel_nonpositive (T : E →ₗ[ℝ] E) (hT : T.IsSymmetric) (w : E) (hlocal : ∀ v, ⟪v, T v⟫ ≤ ⟪T v, T v⟫) (hcon : ∀ v, ⟪v, T v⟫ ≤ ⟪v, v⟫) (heq : ∀ v, ⟪v, T v⟫ = ⟪v, v⟫ → ∃ a : ℝ, v = a • w) (v : E) (hv : ⟪w,v⟫ = 0) : ⟪v, T v⟫ ≤ 0 := by let b := hT.eigenvectorBasis (rfl : Module.finrank ℝ E = Module.finrank ℝ E) let ev := hT.eigenvalues (rfl : Module.finrank ℝ E = Module.finrank ℝ E) have heigen : ∀ i, T (b i) = ev i • b i := hT.apply_eigenvectorBasis rfl have hunit : ∀ i, ⟪b i, b i⟫ = 1 := by intro i rw [real_inner_self_eq_norm_sq, b.orthonormal.1 i] norm_num have hpos : ∀ i, 0 < ev i → b.repr v i = 0 := by intro i hi have hl := hlocal (b i) have hc := hcon (b i) rw [heigen i] at hl hc simp only [inner_smul_left, inner_smul_right, hunit, conj_trivial, mul_one] at hl hc have he : ev i = 1 := by nlinarith have he' : ⟪b i, T (b i)⟫ = ⟪b i, b i⟫ := by rw [heigen i, he, one_smul] obtain ⟨a, ha⟩ := heq (b i) he' rw [b.repr_apply_apply, ha, inner_smul_left, hv] simp rw [← b.repr.inner_map_map v (T v)] simp only [PiLp.inner_apply, RCLike.inner_apply, conj_trivial] apply Finset.sum_nonpos intro i _ have ht : b.repr (T v) i = ev i * b.repr v i := hT.eigenvectorBasis_apply_self_apply rfl v i rw [ht] by_cases h : 0 < ev i · simp [hpos i h] · have hn : ev i ≤ 0 := le_of_not_gt h nlinarith [sq_nonneg (b.repr v i)] end Spectral section PositiveMatrix variable {ι : Type*} [Fintype ι] [sectionInstance7 : DecidableEq ι] theorem matrix_bilin_symm (A : Matrix ι ι ℝ) (hA : ∀ i j, A i j = A j i) : A.toBilin'.IsSymm := by constructor intro x y simp only [Matrix.toBilin'_apply] rw [Finset.sum_comm] apply Finset.sum_congr rfl intro i _ apply Finset.sum_congr rfl intro j _ rw [hA j i] ring def weightedSumLinear (a : ι → ℝ) : (ι → ℝ) →ₗ[ℝ] ℝ where toFun v := ∑ i, a i * v i map_add' x y := by simp [mul_add, Finset.sum_add_distrib] map_smul' c x := by simp [Finset.mul_sum, mul_left_comm] omit sectionInstance7 in lemma dirichlet_identity [DecidableEq ι] (A : Matrix ι ι ℝ) (hA : ∀ i j, A i j = A j i) (r : ι → ℝ) : (∑ i, ∑ j, A i j * (r i-r j)^2) = 2*(∑ i, (∑ j, A i j)*(r i)^2) - 2*(∑ i, ∑ j, r i*A i j*r j) := by have hfirst : (∑ i, ∑ j, A i j*(r i)^2) = ∑ i, (∑ j, A i j)*(r i)^2 := by simp only [Finset.sum_mul] have hsecond : (∑ i, ∑ j, A i j*(r j)^2) = ∑ i, (∑ j, A i j)*(r i)^2 := by rw [Finset.sum_comm] simp_rw [hA] exact hfirst calc _ = ∑ i, ∑ j, (A i j*(r i)^2 + A i j*(r j)^2 - 2*(r i*A i j*r j)) := by apply Finset.sum_congr rfl intro i _ apply Finset.sum_congr rfl intro j _ ring _ = _ := by simp only [Finset.sum_sub_distrib, Finset.sum_add_distrib, ← Finset.mul_sum] rw [hfirst, hsecond] ring lemma eigen_dirichlet (A : Matrix ι ι ℝ) (hA : ∀ i j, A i j = A j i) (w v : ι → ℝ) (hw : ∀ i, 0 < w i) (he : A *ᵥ w = w) : (∑ i, ∑ j, A i j*w i*w j*(v i/w i-v j/w j)^2) = 2 * ((∑ i, (v i)^2) - A.toBilin' v v) := by have hs : ∀ i j, A i j*w i*w j = A j i*w j*w i := by intro i j; rw [hA i j]; ring rw [dirichlet_identity (fun i j => A i j*w i*w j) hs (fun i => v i/w i)] have hrows : ∀ i, (∑ j, A i j*w i*w j)*(v i/w i)^2 = (v i)^2 := by intro i have he' : (∑ j, A i j*w j) = w i := congr_fun he i have hsum : (∑ j, A i j*w i*w j) = w i*(∑ j, A i j*w j) := by rw [Finset.mul_sum] apply Finset.sum_congr rfl intro j _ ring rw [hsum, he'] field_simp [ne_of_gt (hw i)] have hquad : (∑ i, ∑ j, (v i/w i)*(A i j*w i*w j)*(v j/w j)) = A.toBilin' v v := by rw [Matrix.toBilin'_apply] apply Finset.sum_congr rfl intro i _ apply Finset.sum_congr rfl intro j _ field_simp [ne_of_gt (hw i), ne_of_gt (hw j)] simp_rw [hrows] rw [hquad] ring lemma positive_eigen_contraction (A : Matrix ι ι ℝ) (hA : ∀ i j, A i j = A j i) (hpos : ∀ i j, 0 ≤ A i j) (w v : ι → ℝ) (hw : ∀ i, 0 < w i) (he : A *ᵥ w = w) : A.toBilin' v v ≤ ∑ i, (v i)^2 := by have hd := eigen_dirichlet A hA w v hw he have hn : 0 ≤ ∑ i, ∑ j, A i j*w i*w j*(v i/w i-v j/w j)^2 := Finset.sum_nonneg fun i _ => Finset.sum_nonneg fun j _ => mul_nonneg (mul_nonneg (mul_nonneg (hpos i j) (hw i).le) (hw j).le) (sq_nonneg _) linarith lemma positive_eigen_equality [Nonempty ι] (A : Matrix ι ι ℝ) (hA : ∀ i j, A i j = A j i) (hnonneg : ∀ i j, 0 ≤ A i j) (hpos : ∀ i j, i ≠ j → 0 < A i j) (w v : ι → ℝ) (hw : ∀ i, 0 < w i) (he : A *ᵥ w = w) (heq : A.toBilin' v v = ∑ i, (v i)^2) : ∃ a : ℝ, v = a • w := by classical let k : ι := Classical.choice ‹Nonempty ι› have hd := eigen_dirichlet A hA w v hw he rw [heq, sub_self, mul_zero] at hd have hn : ∀ i j, 0 ≤ A i j*w i*w j*(v i/w i-v j/w j)^2 := by intro i j exact mul_nonneg (mul_nonneg (mul_nonneg (hnonneg i j) (hw i).le) (hw j).le) (sq_nonneg _) have h0 : ∀ i j, A i j*w i*w j*(v i/w i-v j/w j)^2 = 0 := by have hrow := (Finset.sum_eq_zero_iff_of_nonneg (fun i (_ : i ∈ Finset.univ) => Finset.sum_nonneg fun j _ => hn i j)).mp hd intro i j exact (Finset.sum_eq_zero_iff_of_nonneg (fun j _ => hn i j)).mp (hrow i (Finset.mem_univ i)) j (Finset.mem_univ j) refine ⟨v k/w k, ?_⟩ ext i simp only [Pi.smul_apply, smul_eq_mul] by_cases hik : i = k · subst i field_simp [ne_of_gt (hw k)] · have hm : A i k*w i*w k ≠ 0 := ne_of_gt (mul_pos (mul_pos (hpos i k hik) (hw i)) (hw k)) have hz : (v i/w i-v k/w k)^2 = 0 := (mul_eq_zero.mp (h0 i k)).resolve_left hm have hh : v i/w i = v k/w k := sub_eq_zero.mp (sq_eq_zero_iff.mp hz) exact (div_eq_iff (ne_of_gt (hw i))).mp hh lemma euclidean_inner_matrix (A : Matrix ι ι ℝ) (v w : EuclideanSpace ℝ ι) : ⟪v, A.toEuclideanLin w⟫ = A.toBilin' (WithLp.ofLp v) (WithLp.ofLp w) := by simp only [PiLp.inner_apply, RCLike.inner_apply, conj_trivial, Matrix.toLpLin_apply, Matrix.mulVec, dotProduct, Matrix.toBilin'_apply, Finset.sum_mul] apply Finset.sum_congr rfl intro i _ apply Finset.sum_congr rfl intro j _ ring omit sectionInstance7 in lemma euclidean_normsq [DecidableEq ι] (v : EuclideanSpace ℝ ι) : ⟪v,v⟫ = ∑ i, (WithLp.ofLp v i)^2 := by simp only [PiLp.inner_apply, RCLike.inner_apply, conj_trivial, pow_two] theorem matrix_signature_of_squared [Nonempty ι] (A : Matrix ι ι ℝ) (hA : ∀ i j, A i j = A j i) (hnonneg : ∀ i j, 0 ≤ A i j) (hpos : ∀ i j, i ≠ j → 0 < A i j) (w : ι → ℝ) (hw : ∀ i, 0 < w i) (he : A *ᵥ w = w) (hlocal : ∀ v, A.toBilin' v v ≤ ∑ i, ((A *ᵥ v) i)^2) : OnePositive A.toBilin' := by have hsym : A.toEuclideanLin.IsSymmetric := by apply Matrix.isSymmetric_toEuclideanLin_iff.mpr ext i j simpa using hA j i refine onePositive_of_nonpositive_kernel _ (matrix_bilin_symm A hA) (weightedSumLinear w) ?_ intro v hv change (∑ i, w i * v i) = 0 at hv have hn := spectral_kernel_nonpositive A.toEuclideanLin hsym (WithLp.toLp 2 w) (fun v => ?_) (fun v => ?_) (fun v hv => ?_) (WithLp.toLp 2 v) ?_ · simpa only [euclidean_inner_matrix, WithLp.ofLp_toLp] using hn · rw [euclidean_inner_matrix, euclidean_normsq] exact hlocal _ · rw [euclidean_inner_matrix, euclidean_normsq] exact positive_eigen_contraction A hA hnonneg w _ hw he · rw [euclidean_inner_matrix, euclidean_normsq] at hv obtain ⟨a, ha⟩ := positive_eigen_equality A hA hnonneg hpos w _ hw he hv refine ⟨a, ?_⟩ exact WithLp.ofLp_injective 2 ha · simpa [PiLp.inner_apply, RCLike.inner_apply, mul_comm] using hv def diagonalScale (A : Matrix ι ι ℝ) (s : ι → ℝ) : Matrix ι ι ℝ := fun i j => s i * A i j * s j lemma diagonalScale_bilin (A : Matrix ι ι ℝ) (s u v : ι → ℝ) : (diagonalScale A s).toBilin' u v = A.toBilin' (fun i => s i*u i) (fun i => s i*v i) := by simp only [Matrix.toBilin'_apply, diagonalScale] apply Finset.sum_congr rfl intro i _ apply Finset.sum_congr rfl intro j _ ring omit sectionInstance7 in lemma diagonalScale_mulVec [DecidableEq ι] (A : Matrix ι ι ℝ) (s v : ι → ℝ) (i : ι) : (diagonalScale A s *ᵥ v) i = s i * (A *ᵥ (fun j => s j*v j)) i := by simp only [Matrix.mulVec, dotProduct, diagonalScale, Finset.mul_sum] apply Finset.sum_congr rfl intro j _ ring lemma onePositive_unscale (A : Matrix ι ι ℝ) (s : ι → ℝ) (hs : ∀ i, s i ≠ 0) (h : OnePositive (diagonalScale A s).toBilin') : OnePositive A.toBilin' := by have hf : ∀ v : ι → ℝ, (fun i => s i * (v i / s i)) = v := by intro v; ext i; field_simp [hs i] intro e he v hv have hep : 0 < (diagonalScale A s).toBilin' (fun i => e i/s i) (fun i => e i/s i) := by simpa [diagonalScale_bilin, hf] using he have hvp : (diagonalScale A s).toBilin' (fun i => v i/s i) (fun i => e i/s i) = 0 := by simpa [diagonalScale_bilin, hf] using hv simpa [diagonalScale_bilin, hf] using h _ hep _ hvp theorem signature_of_local_bound [Nonempty ι] (A : Matrix ι ι ℝ) (hA : ∀ i j, A i j = A j i) (hnonneg : ∀ i j, 0 ≤ A i j) (hpos : ∀ i j, i ≠ j → 0 < A i j) (x s : ι → ℝ) (hx : ∀ i, 0 < x i) (hs : ∀ i, 0 < s i) (hsx : ∀ i, (s i)^2*(A*ᵥx) i = x i) (hlocal : ∀ v, A.toBilin' v v ≤ ∑ i, (s i)^2*((A *ᵥ v) i)^2) : OnePositive A.toBilin' := by let B := diagonalScale A s have hB : ∀ i j, B i j = B j i := by intro i j; dsimp [B, diagonalScale]; rw [hA i j]; ring have hBn : ∀ i j, 0 ≤ B i j := by intro i j; exact mul_nonneg (mul_nonneg (hs i).le (hnonneg i j)) (hs j).le have hBp : ∀ i j, i ≠ j → 0 < B i j := by intro i j hij; exact mul_pos (mul_pos (hs i) (hpos i j hij)) (hs j) let w : ι → ℝ := fun i => x i/s i have hw : ∀ i, 0 < w i := fun i => div_pos (hx i) (hs i) have hsw : (fun j => s j * w j) = x := by ext j; dsimp [w]; field_simp [ne_of_gt (hs j)] have he : B *ᵥ w = w := by ext i rw [diagonalScale_mulVec, hsw] dsimp [w] apply (eq_div_iff (ne_of_gt (hs i))).mpr nlinarith [hsx i] have hl : ∀ v, B.toBilin' v v ≤ ∑ i, ((B *ᵥ v) i)^2 := by intro v change (diagonalScale A s).toBilin' v v ≤ _ dsimp only [B] rw [diagonalScale_bilin] simp_rw [diagonalScale_mulVec, mul_pow] exact hlocal _ exact onePositive_unscale A s (fun i => ne_of_gt (hs i)) (matrix_signature_of_squared B hB hBn hBp w hw he hl) lemma onePositive_quadratic_bound {V : Type*} [AddCommGroup V] [Module ℝ V] (B : LinearMap.BilinForm ℝ V) (hB : OnePositive B) (hS : B.IsSymm) (e v : V) (he : 0 < B e e) : B v v ≤ (B v e)^2 / B e e := by have hz : B ((B e e) • v - (B v e) • e) e = 0 := by simp only [map_sub, map_smul, LinearMap.sub_apply, LinearMap.smul_apply, smul_eq_mul] ring have hn := hB e he ((B e e) • v - (B v e) • e) hz have hev : B e v = B v e := hS.eq e v simp only [map_sub, map_smul, LinearMap.sub_apply, LinearMap.smul_apply, smul_eq_mul, hev] at hn apply (le_div_iff₀ he).mpr have hf : B e e * (B v v * B e e - (B v e)^2) ≤ 0 := by nlinarith [hn] have hle : B v v * B e e - (B v e)^2 ≤ 0 := nonpos_of_mul_nonpos_right hf he linarith def cubicContraction (C : ι → Matrix ι ι ℝ) (x : ι → ℝ) : Matrix ι ι ℝ := fun j k => ∑ i, x i*C i j k omit sectionInstance7 in lemma cubicContraction_symm [DecidableEq ι] (C : ι → Matrix ι ι ℝ) (hC : ∀ i j k, C i j k = C i k j) (x : ι → ℝ) : ∀ j k, cubicContraction C x j k = cubicContraction C x k j := by intro j k simp only [cubicContraction, hC] lemma cubicContraction_bilin (C : ι → Matrix ι ι ℝ) (x v : ι → ℝ) : (cubicContraction C x).toBilin' v v = ∑ i, x i*(C i).toBilin' v v := by calc _ = ∑ j, ∑ k, ∑ i, v j * x i * C i j k * v k := by simp only [Matrix.toBilin'_apply, cubicContraction, Finset.mul_sum, Finset.sum_mul] apply Finset.sum_congr rfl intro j _ apply Finset.sum_congr rfl intro k _ apply Finset.sum_congr rfl intro i _ ring _ = ∑ j, ∑ i, ∑ k, v j * x i * C i j k * v k := Finset.sum_congr rfl fun _ _ => Finset.sum_comm _ = ∑ i, ∑ j, ∑ k, v j * x i * C i j k * v k := Finset.sum_comm _ = _ := by simp only [Matrix.toBilin'_apply, Finset.mul_sum] apply Finset.sum_congr rfl intro i _ apply Finset.sum_congr rfl intro j _ apply Finset.sum_congr rfl intro k _ ring lemma cubicContraction_row (C : ι → Matrix ι ι ℝ) (hC : ∀ i j k, C i j k = C j i k) (x v : ι → ℝ) (i : ι) : (C i).toBilin' x v = (cubicContraction C x *ᵥ v) i := by simp only [Matrix.toBilin'_apply, Matrix.mulVec, dotProduct, cubicContraction, Finset.sum_mul] rw [Finset.sum_comm] apply Finset.sum_congr rfl intro j _ apply Finset.sum_congr rfl intro k _ rw [hC i k j] theorem cubic_local_estimate (C : ι → Matrix ι ι ℝ) (hCs : ∀ i j k, C i j k = C i k j) (hCt : ∀ i j k, C i j k = C j i k) (hC : ∀ i, OnePositive (C i).toBilin') (x : ι → ℝ) (hx : ∀ i, 0 ≤ x i) (hCx : ∀ i, 0 < (C i).toBilin' x x) (v : ι → ℝ) : (cubicContraction C x).toBilin' v v ≤ ∑ i, x i * ((cubicContraction C x *ᵥv) i)^2 / (cubicContraction C x *ᵥx) i := by rw [cubicContraction_bilin] apply Finset.sum_le_sum intro i _ have hS := matrix_bilin_symm (C i) (hCs i) have hl := mul_le_mul_of_nonneg_left (onePositive_quadratic_bound (C i).toBilin' (hC i) hS x v (hCx i)) (hx i) rw [hS.eq v x, cubicContraction_row C hCt x v i, cubicContraction_row C hCt x x i, ← mul_div_assoc] at hl exact hl theorem cubic_signature [Nonempty ι] (C : ι → Matrix ι ι ℝ) (hCs : ∀ i j k, C i j k = C i k j) (hCt : ∀ i j k, C i j k = C j i k) (hC : ∀ i, OnePositive (C i).toBilin') (x : ι → ℝ) (hx : ∀ i, 0 < x i) (hCx : ∀ i, 0 < (C i).toBilin' x x) (hCn : ∀ j k, 0 ≤ cubicContraction C x j k) (hCp : ∀ j k, j ≠ k → 0 < cubicContraction C x j k) : OnePositive (cubicContraction C x).toBilin' := by let A := cubicContraction C x have hy : ∀ i, 0 < (A*ᵥx) i := by intro i rw [← cubicContraction_row C hCt x x i] exact hCx i let s : ι → ℝ := fun i => Real.sqrt (x i/(A*ᵥx) i) have hs : ∀ i, 0 < s i := fun i => Real.sqrt_pos.2 (div_pos (hx i) (hy i)) have hs2 : ∀ i, (s i)^2 = x i/(A*ᵥx) i := fun i => Real.sq_sqrt (le_of_lt (div_pos (hx i) (hy i))) apply signature_of_local_bound A (cubicContraction_symm C hCs x) hCn hCp x s hx hs · intro i rw [hs2] field_simp [ne_of_gt (hy i)] intro v have hl := cubic_local_estimate C hCs hCt hC x (fun i => (hx i).le) hCx v refine hl.trans_eq ?_ apply Finset.sum_congr rfl intro i _ rw [hs2] ring end PositiveMatrix section RawSignature open scoped BigOperators Classical variable {ι : Type*} [sectionInstance8 : Fintype ι] [sectionInstance9 : DecidableEq ι] noncomputable def rankWeight (M : Matroid ι) (q : ℝ) (A : Set ι) : ℝ := (q⁻¹) ^ (M.eRk A).toNat noncomputable def rawHessian (M : Matroid ι) (q : ℝ) : Matrix ι ι ℝ := fun i j => if i = j then 0 else rankWeight M q {i,j} omit sectionInstance8 sectionInstance9 in lemma eRk_insert_of_mem_closure' [Fintype ι] [DecidableEq ι] (M : Matroid ι) (i : ι) (X : Set ι) (hi : i ∈ M.closure X) : M.eRk (insert i X) = M.eRk X := by rw [← M.eRk_insert_closure_eq, Set.insert_eq_of_mem hi, M.eRk_closure_eq] lemma pair_rank_of_loop (M : Matroid ι) (i j : ι) (hi : M.IsLoop i) : M.eRk {i,j} = M.eRk {j} := eRk_insert_of_mem_closure' M i {j} (hi.mem_closure _) lemma pair_rank_parallel (M : Matroid ι) (i j : ι) (hi : M.IsNonloop i) (hj : M.IsNonloop j) (hc : M.closure {i} = M.closure {j}) : M.eRk {i,j} = 1 := by rw [eRk_insert_of_mem_closure' M i {j}, hj.eRk_eq] rw [← hc] exact M.mem_closure_self i hi.mem_ground omit sectionInstance8 sectionInstance9 in lemma pair_rank_nonparallel [Fintype ι] [DecidableEq ι] (M : Matroid ι) (i j : ι) (hi : M.IsNonloop i) (hj : M.IsNonloop j) (hc : M.closure {i} ≠ M.closure {j}) : M.eRk {i,j} = 2 := by have hn : i ∉ M.closure {j} := fun h => hc (hi.closure_eq_of_mem_closure h) rw [M.eRk_insert_eq_add_one ⟨hi.mem_ground, hn⟩, hj.eRk_eq] norm_num noncomputable def rawPositive (M : Matroid ι) (q : ℝ) (i : ι) : ℝ := if M.IsNonloop i then q⁻¹ else 1 noncomputable def parallelIndicator (M : Matroid ι) (C : Set ι) (i : ι) : ℝ := if M.IsNonloop i ∧ M.closure {i} = C then 1 else 0 omit sectionInstance9 in lemma parallel_gram [DecidableEq ι] (M : Matroid ι) (i j : ι) : (∑ C : Set ι, parallelIndicator M C i * parallelIndicator M C j) = if M.IsNonloop i ∧ M.IsNonloop j ∧ M.closure {i} = M.closure {j} then 1 else 0 := by classical by_cases hi : M.IsNonloop i <;> by_cases hj : M.IsNonloop j · simp [parallelIndicator, hi, hj, Finset.sum_ite_eq', eq_comm] · simp [parallelIndicator, hi, hj] · simp [parallelIndicator, hi, hj] · simp [parallelIndicator, hi, hj] lemma rawHessian_decomposition (M : Matroid ι) (hE : M.E = Set.univ) (q : ℝ) (i j : ι) : rawHessian M q i j = rawPositive M q i * rawPositive M q j - (if i = j then rawPositive M q i else 0) - (q⁻¹^2-q⁻¹) * ∑ C : Set ι, parallelIndicator M C i * parallelIndicator M C j := by classical have hground : ∀ i, i ∈ M.E := by simp [hE] rw [parallel_gram] by_cases hij : i = j · subst j by_cases hi : M.IsNonloop i <;> simp [rawHessian, rawPositive, hi] ; ring · have hij' : j ≠ i := Ne.symm hij simp only [rawHessian, ite_eq_right hij] by_cases hi : M.IsNonloop i <;> by_cases hj : M.IsNonloop j · by_cases hc : M.closure {i} = M.closure {j} · rw [rankWeight, pair_rank_parallel M i j hi hj hc] simp [rawPositive, hi, hj, hc] ring · rw [rankWeight, pair_rank_nonparallel M i j hi hj hc] simp [rawPositive, hi, hj, hc] ring · have hloop : M.IsLoop j := (M.not_isNonloop_iff (hground j)).mp hj rw [rankWeight, Set.pair_comm i j, pair_rank_of_loop M j i hloop, hi.eRk_eq] simp [rawPositive, hi, hj] · have hloop : M.IsLoop i := (M.not_isNonloop_iff (hground i)).mp hi rw [rankWeight, pair_rank_of_loop M i j hloop, hj.eRk_eq] simp [rawPositive, hi, hj] · have hli : M.IsLoop i := (M.not_isNonloop_iff (hground i)).mp hi have hlj : M.IsLoop j := (M.not_isNonloop_iff (hground j)).mp hj rw [rankWeight, pair_rank_of_loop M i j hli, hlj.eRk_eq] simp [rawPositive, hi, hj] omit sectionInstance9 in lemma sum_rankone [DecidableEq ι] (a v : ι → ℝ) : (∑ i, ∑ j, v i * (a i * a j) * v j) = (∑ i, a i * v i)^2 := by rw [pow_two, Finset.sum_mul_sum] apply Finset.sum_congr rfl intro i _ apply Finset.sum_congr rfl intro j _ ring lemma sum_diagonal (a v : ι → ℝ) : (∑ i, ∑ j, v i * (if i = j then a i else 0) * v j) = ∑ i, a i * (v i)^2 := by simp only [mul_ite, ite_mul, mul_zero, zero_mul, Finset.sum_ite_eq, Finset.mem_univ, ite_true] apply Finset.sum_congr rfl intro i _ ring lemma sum_gram {κ : Type*} [Fintype κ] (p : κ → ι → ℝ) (v : ι → ℝ) : (∑ i, ∑ j, v i * (∑ c, p c i * p c j) * v j) = ∑ c, (∑ i, p c i * v i)^2 := by calc _ = ∑ i, ∑ j, ∑ c, v i * (p c i * p c j) * v j := by simp only [Finset.mul_sum, Finset.sum_mul] _ = ∑ i, ∑ c, ∑ j, v i * (p c i * p c j) * v j := Finset.sum_congr rfl fun _ _ => Finset.sum_comm _ = ∑ c, ∑ i, ∑ j, v i * (p c i * p c j) * v j := Finset.sum_comm _ = _ := Finset.sum_congr rfl fun c _ => sum_rankone (p c) v lemma rawHessian_eval (M : Matroid ι) (hE : M.E = Set.univ) (q : ℝ) (v : ι → ℝ) : (rawHessian M q).toBilin' v v = (∑ i, rawPositive M q i * v i)^2 - (∑ i, rawPositive M q i * (v i)^2) - (q⁻¹^2-q⁻¹) * ∑ C : Set ι, (∑ i, parallelIndicator M C i * v i)^2 := by simp only [Matrix.toBilin'_apply, rawHessian_decomposition M hE] generalize hc : q⁻¹^2-q⁻¹ = c simp only [mul_sub, sub_mul, Finset.sum_sub_distrib] rw [sum_rankone, sum_diagonal] congr 1 rw [← sum_gram] simp only [Finset.mul_sum] apply Finset.sum_congr rfl intro i _ apply Finset.sum_congr rfl intro j _ simp only [Finset.sum_mul, Finset.mul_sum] apply Finset.sum_congr rfl intro C _ ring theorem raw_matroid_signature (M : Matroid ι) (hE : M.E = Set.univ) (q : ℝ) (hq : 0 < q) (hq1 : q ≤ 1) : OnePositive (rawHessian M q).toBilin' := by refine onePositive_of_nonpositive_kernel _ ?_ (weightedSumLinear (rawPositive M q)) ?_ · apply matrix_bilin_symm intro i j by_cases hij : i = j · subst j; rfl · simp [rawHessian, hij, Ne.symm hij, Set.pair_comm i j] intro v hv change (∑ i, rawPositive M q i * v i) = 0 at hv rw [rawHessian_eval M hE q v, hv, zero_pow (by decide), zero_sub] have hp : ∀ i, 0 ≤ rawPositive M q i := by intro i simp only [rawPositive] split_ifs <;> positivity have hd : 0 ≤ ∑ i, rawPositive M q i * (v i)^2 := Finset.sum_nonneg fun i _ => mul_nonneg (hp i) (sq_nonneg _) have hi : 1 ≤ q⁻¹ := (one_le_inv₀ hq).mpr hq1 have hc : 0 ≤ q⁻¹^2-q⁻¹ := by nlinarith have hg : 0 ≤ (q⁻¹^2-q⁻¹) * ∑ C : Set ι, (∑ i, parallelIndicator M C i * v i)^2 := mul_nonneg hc (Finset.sum_nonneg fun _ _ => sq_nonneg _) linarith end RawSignature section MatroidFaces open scoped Matroid BigOperators Classical variable {ι : Type*} [sectionInstance10 : Fintype ι] [sectionInstance11 : DecidableEq ι] omit sectionInstance10 sectionInstance11 in lemma contract_eRk_add [Fintype ι] [DecidableEq ι] (M : Matroid ι) (A X : Set ι) (hA : A ⊆ M.E) (hX : X ⊆ (M / A).E) : (M / A).eRk X + M.eRk A = M.eRk (X ∪ A) := by obtain ⟨I, hI⟩ := M.exists_isBasis A hA obtain ⟨J, hJ⟩ := (M / A).exists_isBasis X hX have hJ' : (M / I).IsBasis J X := by rw [hI.contract_eq_contract_delete] at hJ exact (Matroid.delete_isBasis_iff.mp hJ).1 have hU := hI.indep.union_isBasis_union_of_contract_isBasis hJ' have hd : Disjoint J I := (hI.indep.contract_indep_iff.mp hJ'.indep).1 calc _ = J.encard + I.encard := by rw [hJ.eRk_eq_encard, hI.eRk_eq_encard] _ = (J ∪ I).encard := (Set.encard_union_eq hd).symm _ = M.eRk (X ∪ I) := hU.encard_eq_eRk _ = M.eRk (X ∪ A) := by simpa [Set.union_comm] using hI.eRk_eq_eRk_union X noncomputable def faceHessian (f : Set ι → ℝ) (A : Set ι) : Matrix {i // i ∉ A} {i // i ∉ A} ℝ := fun i j => if i = j then 0 else f (A ∪ {i.val,j.val}) noncomputable def faceMatroid (M : Matroid ι) (A : Set ι) : Matroid {i // i ∉ A} := (M / A).comap Subtype.val omit sectionInstance10 sectionInstance11 in lemma faceMatroid_ground [Fintype ι] [DecidableEq ι] (M : Matroid ι) (hE : M.E = Set.univ) (A : Set ι) : (faceMatroid M A).E = Set.univ := by ext i simp [faceMatroid, hE, i.property] lemma faceMatroid_rank (M : Matroid ι) (hE : M.E = Set.univ) (A : Set ι) (i j : {i // i ∉ A}) : (faceMatroid M A).eRk {i,j} + M.eRk A = M.eRk (A ∪ {i.val,j.val}) := by have hA : A ⊆ M.E := by simp [hE] have hX : ({i.val,j.val} : Set ι) ⊆ (M / A).E := by simp only [Matroid.contract_ground, hE] intro k hk rcases hk with rfl | rfl · exact ⟨Set.mem_univ _, i.property⟩ · exact ⟨Set.mem_univ _, j.property⟩ simpa [faceMatroid, Matroid.eRk_comap, Set.image_pair, Set.union_comm] using contract_eRk_add M A {i.val,j.val} hA hX lemma faceHessian_rankWeight (M : Matroid ι) (hE : M.E = Set.univ) (q : ℝ) (A : Set ι) : faceHessian (rankWeight M q) A = rankWeight M q A • rawHessian (faceMatroid M A) q := by ext i j by_cases hij : i = j · simp [faceHessian, rawHessian, hij] simp only [faceHessian, rawHessian, ite_eq_right hij, Matrix.smul_apply, smul_eq_mul, rankWeight] have hr := faceMatroid_rank M hE A i j rw [← hr, ENat.toNat_add (by simp) (by simp), pow_add, mul_comm] lemma onePositive_pos_smul {V : Type*} [AddCommGroup V] [Module ℝ V] (B : LinearMap.BilinForm ℝ V) (hB : OnePositive B) (c : ℝ) (hc : 0 < c) : OnePositive (c • B) := by intro e he v hv simp only [LinearMap.smul_apply, smul_eq_mul] at he hv ⊢ have he' : 0 < B e e := pos_of_mul_pos_right he hc.le have hv' : B v e = 0 := (mul_eq_zero.mp hv).resolve_left (ne_of_gt hc) exact mul_nonpos_of_nonneg_of_nonpos hc.le (hB e he' v hv') theorem rankWeight_face_signature (M : Matroid ι) (hE : M.E = Set.univ) (q : ℝ) (hq : 0 < q) (hq1 : q ≤ 1) (A : Set ι) : OnePositive (faceHessian (rankWeight M q) A).toBilin' := by rw [faceHessian_rankWeight M hE q A, map_smul] exact onePositive_pos_smul _ (raw_matroid_signature (faceMatroid M A) (faceMatroid_ground M hE A) q hq hq1) _ (by dsimp [rankWeight]; positivity) end MatroidFaces section DerivativeClosure open scoped BigOperators Classical Matrix variable {ι : Type*} [sectionInstance12 : Fintype ι] [sectionInstance13 : DecidableEq ι] noncomputable def coeffDeriv (a : ι → ℝ) (f : Set ι → ℝ) (A : Set ι) : ℝ := ∑ i, if i ∈ A then 0 else a i * f (insert i A) noncomputable def coeffDerivs : List (ι → ℝ) → (Set ι → ℝ) → Set ι → ℝ | [], f => f | a :: as, f => coeffDeriv a (coeffDerivs as f) omit sectionInstance13 in lemma card_outside [DecidableEq ι] (A : Set ι) : Fintype.card {i // i ∉ A} + A.ncard = Fintype.card ι := by change Fintype.card (Aᶜ : Set ι) + A.ncard = Fintype.card ι rw [Set.fintypeCard_eq_ncard] simpa [Nat.card_eq_fintype_card, add_comm] using A.ncard_add_ncard_compl omit sectionInstance13 in lemma ncard_insert_eq [DecidableEq ι] (A : Set ι) (i : ι) (hi : i ∉ A) : (insert i A).ncard = A.ncard + 1 := Set.ncard_insert_of_notMem hi omit sectionInstance13 in lemma exists_outside_of_ncard_lt [DecidableEq ι] (A : Set ι) (h : A.ncard < Fintype.card ι) : ∃ i, i ∉ A := by by_contra hn have hA : A = Set.univ := by ext i; simp only [Set.mem_univ, iff_true]; exact of_not_not (not_exists.mp hn i) simp [hA] at h def FullPositive (f : Set ι → ℝ) (k : ℕ) : Prop := (∀ A, A.ncard + k ≤ Fintype.card ι → 0 < f A) ∧ (∀ A, Fintype.card ι < A.ncard + k → f A = 0) omit sectionInstance13 in lemma FullPositive.nonneg [DecidableEq ι] {f : Set ι → ℝ} {k : ℕ} (h : FullPositive f k) (A : Set ι) : 0 ≤ f A := by by_cases ha : A.ncard + k ≤ Fintype.card ι · exact (h.1 A ha).le · rw [h.2 A (lt_of_not_ge ha)] lemma FullPositive.deriv {f : Set ι → ℝ} {k : ℕ} (h : FullPositive f k) (a : ι → ℝ) (ha : ∀ i, 0 < a i) : FullPositive (coeffDeriv a f) (k+1) := by constructor · intro A hA obtain ⟨i, hi⟩ := exists_outside_of_ncard_lt A (by omega) apply Finset.sum_pos' · intro j _ split_ifs · exact le_rfl · exact mul_nonneg (ha j).le (h.nonneg _) · refine ⟨i, Finset.mem_univ _, ?_⟩ rw [ite_eq_right hi] apply mul_pos (ha i) apply h.1 rw [ncard_insert_eq A i hi] omega · intro A hA apply Finset.sum_eq_zero intro i _ split_ifs with hi · rfl · rw [h.2 (insert i A) (by rw [ncard_insert_eq A i hi]; omega), mul_zero] lemma onePositive_comap {V W : Type*} [AddCommGroup V] [Module ℝ V] [AddCommGroup W] [Module ℝ W] (B : LinearMap.BilinForm ℝ V) (hB : OnePositive B) (L : W →ₗ[ℝ] V) : OnePositive (B.compl₁₂ L L) := by intro e he v hv exact hB (L e) he (L v) hv noncomputable def padMatrix (p : ι → Prop) [DecidablePred p] (B : Matrix {i // p i} {i // p i} ℝ) : Matrix ι ι ℝ := fun i j => if hi : p i then if hj : p j then B ⟨i,hi⟩ ⟨j,hj⟩ else 0 else 0 lemma padMatrix_bilin (p : ι → Prop) [DecidablePred p] (B : Matrix {i // p i} {i // p i} ℝ) (v w : ι → ℝ) : (padMatrix p B).toBilin' v w = B.toBilin' (fun i => v i.val) (fun i => w i.val) := by simp only [Matrix.toBilin'_apply] rw [← Fintype.sum_subtype_add_sum_subtype p (fun i => ∑ j, v i * padMatrix p B i j * w j)] have hn : (∑ i : {i // ¬p i}, ∑ j, v i.val * padMatrix p B i.val j * w j) = 0 := by apply Finset.sum_eq_zero intro i _ apply Finset.sum_eq_zero intro j _ simp [padMatrix, i.property] rw [hn, add_zero] apply Finset.sum_congr rfl intro i _ rw [← Fintype.sum_subtype_add_sum_subtype p (fun j => v i.val * padMatrix p B i.val j * w j)] have hn' : (∑ j : {j // ¬p j}, v i.val * padMatrix p B i.val j.val * w j.val) = 0 := by apply Finset.sum_eq_zero intro j _ simp [padMatrix, i.property, j.property] rw [hn', add_zero] apply Finset.sum_congr rfl intro j _ simp [padMatrix, i.property, j.property] lemma onePositive_padMatrix (p : ι → Prop) [DecidablePred p] (B : Matrix {i // p i} {i // p i} ℝ) (hB : OnePositive B.toBilin') : OnePositive (padMatrix p B).toBilin' := by intro e he v hv rw [padMatrix_bilin] at he hv ⊢ exact hB _ he _ hv lemma matrix_reindex_bilin {κ : Type*} [Fintype κ] (e : ι ≃ κ) (B : Matrix κ κ ℝ) (v w : ι → ℝ) : (B.submatrix e e).toBilin' v w = B.toBilin' (fun j => v (e.symm j)) (fun j => w (e.symm j)) := by simp only [Matrix.toBilin'_apply, Matrix.submatrix_apply] apply Fintype.sum_equiv e intro i apply Fintype.sum_equiv e intro j simp lemma onePositive_reindex {κ : Type*} [Fintype κ] (e : ι ≃ κ) (B : Matrix κ κ ℝ) (hB : OnePositive B.toBilin') : OnePositive (B.submatrix e e).toBilin' := by intro x hx v hv rw [matrix_reindex_bilin] at hx hv ⊢ exact hB _ hx _ hv noncomputable def faceEraseEquiv (A : Set ι) (i : {i // i ∉ A}) : {j : {j // j ∉ A} // j ≠ i} ≃ {j // j ∉ insert i.val A} where toFun j := ⟨j.val.val, by simp only [Set.mem_insert_iff, not_or] exact ⟨fun h => j.property (Subtype.ext h), j.val.property⟩⟩ invFun j := ⟨⟨j.val, fun h => j.property (Set.mem_insert_of_mem _ h)⟩, fun h => j.property (Or.inl (congrArg Subtype.val h))⟩ left_inv j := rfl right_inv j := rfl noncomputable def faceCubic (f : Set ι → ℝ) (A : Set ι) : {i // i ∉ A} → Matrix {i // i ∉ A} {i // i ∉ A} ℝ := fun i j k => if i = j ∨ i = k ∨ j = k then 0 else f (insert i.val (A ∪ {j.val,k.val})) omit sectionInstance12 in lemma faceCubic_symm [Fintype ι] (f : Set ι → ℝ) (A : Set ι) (i j k : {i // i ∉ A}) : faceCubic f A i j k = faceCubic f A i k j := by unfold faceCubic have hc : (i = j ∨ i = k ∨ j = k) ↔ (i = k ∨ i = j ∨ k = j) := by aesop simp only [← hc] have hs : ({j.val,k.val} : Set ι) = {k.val,j.val} := Set.pair_comm _ _ rw [hs] omit sectionInstance12 in lemma faceCubic_transpose [Fintype ι] (f : Set ι → ℝ) (A : Set ι) (i j k : {i // i ∉ A}) : faceCubic f A i j k = faceCubic f A j i k := by unfold faceCubic have hc : (i = j ∨ i = k ∨ j = k) ↔ (j = i ∨ j = k ∨ i = k) := by aesop simp only [← hc] have hs : insert i.val (A ∪ {j.val,k.val}) = insert j.val (A ∪ {i.val,k.val}) := by ext x; simp; tauto rw [hs] omit sectionInstance12 in lemma faceCubic_pad [Fintype ι] (f : Set ι → ℝ) (A : Set ι) (i : {i // i ∉ A}) : faceCubic f A i = padMatrix (fun j => j ≠ i) ((faceHessian f (insert i.val A)).submatrix (faceEraseEquiv A i) (faceEraseEquiv A i)) := by ext j k simp only [faceCubic, padMatrix] by_cases hji : j = i · subst j; simp by_cases hki : k = i · subst k; simp rw [dite_eq_left hji, dite_eq_left hki] simp only [Matrix.submatrix_apply, faceHessian] by_cases hjk : j = k · subst k; simp have hi : i ≠ j := Ne.symm hji have hk : i ≠ k := Ne.symm hki have hne : faceEraseEquiv A i ⟨j,hji⟩ ≠ faceEraseEquiv A i ⟨k,hki⟩ := by intro h exact hjk (congrArg Subtype.val ((faceEraseEquiv A i).injective h)) simp only [hi, hk, hjk, false_or, ite_false, hne] congr 1 ext x simp [faceEraseEquiv] tauto lemma faceCubic_onePositive (f : Set ι → ℝ) (hf : ∀ A, OnePositive (faceHessian f A).toBilin') (A : Set ι) (i : {i // i ∉ A}) : OnePositive (faceCubic f A i).toBilin' := by classical rw [faceCubic_pad] apply onePositive_padMatrix apply onePositive_reindex convert hf (insert i.val A) using 1 congr 2 <;> exact Subsingleton.elim _ _ omit sectionInstance13 in lemma ncard_union_pair [DecidableEq ι] (A : Set ι) (i j : {i // i ∉ A}) (hij : i ≠ j) : (A ∪ {i.val,j.val}).ncard = A.ncard + 2 := by have he : A ∪ {i.val,j.val} = insert i.val (insert j.val A) := by ext x; simp have hne : i.val ≠ j.val := fun h => hij (Subtype.ext h) rw [he, Set.ncard_insert_of_notMem (by simpa using And.intro hne i.property), Set.ncard_insert_of_notMem j.property] lemma ncard_insert_union_pair (A : Set ι) (i j k : {i // i ∉ A}) (hij : i ≠ j) (hik : i ≠ k) (hjk : j ≠ k) : (insert i.val (A ∪ {j.val,k.val})).ncard = A.ncard + 3 := by have hi : i.val ∉ A ∪ {j.val,k.val} := by simp only [Set.mem_union, Set.mem_insert_iff, Set.mem_singleton_iff, not_or] exact ⟨i.property, fun h => hij (Subtype.ext h), fun h => hik (Subtype.ext h)⟩ rw [Set.ncard_insert_of_notMem hi, ncard_union_pair A j k hjk] lemma faceCubic_contraction (f : Set ι → ℝ) (a : ι → ℝ) (A : Set ι) (j k : {i // i ∉ A}) : faceHessian (coeffDeriv a f) A j k = ∑ i : {i // i ∉ A}, a i.val * faceCubic f A i j k := by classical by_cases hjk : j = k · subst k; simp [faceHessian, faceCubic] change (if j = k then 0 else coeffDeriv a f (A ∪ {j.val,k.val})) = _ rw [ite_eq_right hjk] unfold coeffDeriv let g : ι → ℝ := fun i => @ite ℝ (i ∈ A ∪ {j.val,k.val}) (Classical.propDecidable _) 0 (a i * f (insert i (A ∪ {j.val,k.val}))) change (∑ i, g i) = _ rw [← Fintype.sum_subtype_add_sum_subtype (fun i => i ∉ A) g] have hz : (∑ i : {i // ¬i ∉ A}, g i.val) = 0 := by apply Finset.sum_eq_zero intro i _ dsimp [g] rw [ite_eq_left (Set.mem_union_left _ (not_not.mp i.property))] rw [hz, add_zero] apply Finset.sum_congr rfl intro i _ dsimp only [g] by_cases hij : i = j · subst j; simp [faceCubic] by_cases hik : i = k · subst k; simp [faceCubic] have hni : i.val ∉ A ∪ {j.val,k.val} := by simp only [Set.mem_union, Set.mem_insert_iff, Set.mem_singleton_iff, not_or] exact ⟨i.property, fun h => hij (Subtype.ext h), fun h => hik (Subtype.ext h)⟩ simp only [ite_eq_right hni, faceCubic, hij, hik, hjk, false_or, ite_false] omit sectionInstance12 in lemma faceCubic_nonneg [Fintype ι] (f : Set ι → ℝ) (hf : ∀ A, 0 ≤ f A) (A : Set ι) (i j k : {i // i ∉ A}) : 0 ≤ faceCubic f A i j k := by unfold faceCubic split_ifs · exact le_rfl · exact hf _ lemma FullPositive.faceCubic_pos {f : Set ι → ℝ} {m : ℕ} (hf : FullPositive f m) (A : Set ι) (hA : A.ncard + m + 3 ≤ Fintype.card ι) (i j k : {i // i ∉ A}) (hij : i ≠ j) (hik : i ≠ k) (hjk : j ≠ k) : 0 < faceCubic f A i j k := by simp only [faceCubic, hij, hik, hjk, false_or, ite_false] apply hf.1 rw [ncard_insert_union_pair A i j k hij hik hjk] omega lemma FullPositive.faceCubic_zero {f : Set ι → ℝ} {m : ℕ} (hf : FullPositive f m) (A : Set ι) (hA : Fintype.card ι < A.ncard + m + 3) (i j k : {i // i ∉ A}) : faceCubic f A i j k = 0 := by unfold faceCubic split_ifs with hc · rfl · obtain ⟨hij,hik,hjk⟩ : i ≠ j ∧ i ≠ k ∧ j ≠ k := by tauto apply hf.2 rw [ncard_insert_union_pair A i j k hij hik hjk] omega theorem derivative_face_signature {f : Set ι → ℝ} {m : ℕ} (hf : FullPositive f m) (hfs : ∀ A, OnePositive (faceHessian f A).toBilin') (a : ι → ℝ) (ha : ∀ i, 0 < a i) (A : Set ι) : OnePositive (faceHessian (coeffDeriv a f) A).toBilin' := by classical have heq : faceHessian (coeffDeriv a f) A = cubicContraction (faceCubic f A) (fun i => a i.val) := by ext j k exact faceCubic_contraction f a A j k rw [heq] by_cases hA : A.ncard + m + 3 ≤ Fintype.card ι · obtain ⟨i, hi⟩ := exists_outside_of_ncard_lt A (by omega) let : Nonempty {i // i ∉ A} := ⟨⟨i,hi⟩⟩ have hn : ∀ j k, 0 ≤ cubicContraction (faceCubic f A) (fun i => a i.val) j k := by intro j k apply Finset.sum_nonneg intro i _ exact mul_nonneg (ha _).le (faceCubic_nonneg f hf.nonneg A i j k) have hp : ∀ j k, j ≠ k → 0 < cubicContraction (faceCubic f A) (fun i => a i.val) j k := by intro j k hjk obtain ⟨l,hl⟩ := exists_outside_of_ncard_lt (A ∪ {j.val,k.val}) (by rw [ncard_union_pair A j k hjk]; omega) have hlA : l ∉ A := fun h => hl (Or.inl h) let l' : {i // i ∉ A} := ⟨l,hlA⟩ have hlj : l' ≠ j := by intro h; exact hl (Or.inr (Or.inl (congrArg Subtype.val h))) have hlk : l' ≠ k := by intro h; exact hl (Or.inr (Or.inr (congrArg Subtype.val h))) apply Finset.sum_pos' · intro i _ exact mul_nonneg (ha _).le (faceCubic_nonneg f hf.nonneg A i j k) · exact ⟨l', Finset.mem_univ _, mul_pos (ha l) (hf.faceCubic_pos A hA l' j k hlj hlk hjk)⟩ apply cubic_signature (faceCubic f A) (faceCubic_symm f A) (faceCubic_transpose f A) (faceCubic_onePositive f hfs A) (fun i => a i.val) (fun i => ha i.val) _ hn hp intro j rw [cubicContraction_row _ (faceCubic_transpose f A)] change 0 < ∑ k, cubicContraction (faceCubic f A) (fun i => a i.val) j k * a k.val obtain ⟨k,hk⟩ := exists_outside_of_ncard_lt (insert j.val A) (by rw [ncard_insert_eq A j.val j.property]; omega) have hkA : k ∉ A := fun h => hk (Or.inr h) let k' : {i // i ∉ A} := ⟨k,hkA⟩ have hjk : j ≠ k' := by intro h; exact hk (Or.inl (congrArg Subtype.val h).symm) apply Finset.sum_pos' · intro k _; exact mul_nonneg (hn j k) (ha _).le · exact ⟨k', Finset.mem_univ _, mul_pos (hp j k' hjk) (ha k)⟩ · have hz : cubicContraction (faceCubic f A) (fun i => a i.val) = 0 := by ext j k simp [cubicContraction, hf.faceCubic_zero A (lt_of_not_ge hA)] rw [hz] intro e he simp omit sectionInstance13 in lemma rankWeight_fullPositive [DecidableEq ι] (M : Matroid ι) (q : ℝ) (hq : 0 < q) : FullPositive (rankWeight M q) 0 := by constructor · intro A _; unfold rankWeight; positivity · intro A hA have hbound : A.ncard ≤ Fintype.card ι := by simpa using Set.ncard_le_card A omega theorem rankWeight_positive_directions (M : Matroid ι) (hE : M.E = Set.univ) (q : ℝ) (hq : 0 < q) (hq1 : q ≤ 1) (ds : List (ι → ℝ)) (hds : ∀ a ∈ ds, ∀ i, 0 < a i) : FullPositive (coeffDerivs ds (rankWeight M q)) ds.length ∧ ∀ A, OnePositive (faceHessian (coeffDerivs ds (rankWeight M q)) A).toBilin' := by induction ds with | nil => exact ⟨rankWeight_fullPositive M q hq, rankWeight_face_signature M hE q hq hq1⟩ | cons a ds ih => have ha := hds a (List.mem_cons_self ..) obtain ⟨hpos,hsig⟩ := ih (fun b hb => hds b (List.mem_cons_of_mem _ hb)) exact ⟨hpos.deriv a ha, derivative_face_signature hpos hsig a ha⟩ lemma matrix_bilin_tendsto {κ : Type*} {l : Filter κ} (F : κ → Matrix ι ι ℝ) (B : Matrix ι ι ℝ) (hF : ∀ i j, Filter.Tendsto (fun t => F t i j) l (nhds (B i j))) (v w : ι → ℝ) : Filter.Tendsto (fun t => (F t).toBilin' v w) l (nhds (B.toBilin' v w)) := by simp only [Matrix.toBilin'_apply] apply tendsto_finsetSum intro i _ apply tendsto_finsetSum intro j _ exact ((tendsto_const_nhds.mul (hF i j)).mul tendsto_const_nhds) lemma onePositive_of_tendsto {κ : Type*} {l : Filter κ} [l.NeBot] (F : κ → Matrix ι ι ℝ) (B : Matrix ι ι ℝ) (hF : ∀ i j, Filter.Tendsto (fun t => F t i j) l (nhds (B i j))) (hS : ∀ t i j, F t i j = F t j i) (hP : ∀ᶠ t in l, OnePositive (F t).toBilin') : OnePositive B.toBilin' := by intro e he v hv have hee := matrix_bilin_tendsto F B hF e e have hvv := matrix_bilin_tendsto F B hF v v have hve := matrix_bilin_tendsto F B hF v e have hp : ∀ᶠ t in l, (F t).toBilin' v v * (F t).toBilin' e e ≤ ((F t).toBilin' v e)^2 := by filter_upwards [hP, hee.eventually (eventually_gt_nhds he)] with t ht hte exact (le_div_iff₀ hte).mp (onePositive_quadratic_bound _ ht (matrix_bilin_symm _ (hS t)) e v hte) have hh := le_of_tendsto_of_tendsto (hvv.mul hee) (hve.pow 2) hp rw [hv, zero_pow (by decide : 2 ≠ 0)] at hh exact nonpos_of_mul_nonpos_right (by simpa [mul_comm] using hh) he omit sectionInstance12 in lemma faceHessian_symm [Fintype ι] (f : Set ι → ℝ) (A : Set ι) : ∀ i j, faceHessian f A i j = faceHessian f A j i := by intro i j simp only [faceHessian] by_cases hij : i = j · subst j; rfl · rw [ite_eq_right hij, ite_eq_right (Ne.symm hij), Set.pair_comm] omit sectionInstance13 in lemma continuous_coeffDerivs_perturb [DecidableEq ι] (ds : List (ι → ℝ)) (f : Set ι → ℝ) (A : Set ι) : Continuous (fun t : ℝ => coeffDerivs (ds.map (fun a i => a i + t)) f A) := by induction ds generalizing A with | nil => exact continuous_const | cons a ds ih => simp only [List.map_cons, coeffDerivs, coeffDeriv] apply continuous_finsetSum intro i _ by_cases hi : i ∈ A · simp only [ite_eq_left hi]; exact continuous_const · simp only [ite_eq_right hi] exact (continuous_const.add continuous_id).mul (ih _) theorem rankWeight_nonnegative_directions (M : Matroid ι) (hE : M.E = Set.univ) (q : ℝ) (hq : 0 < q) (hq1 : q ≤ 1) (ds : List (ι → ℝ)) (hds : ∀ a ∈ ds, ∀ i, 0 ≤ a i) (A : Set ι) : OnePositive (faceHessian (coeffDerivs ds (rankWeight M q)) A).toBilin' := by classical let F : ℝ → Matrix {i // i ∉ A} {i // i ∉ A} ℝ := fun t => faceHessian (coeffDerivs (ds.map (fun a i => a i + t)) (rankWeight M q)) A have hzero : F 0 = faceHessian (coeffDerivs ds (rankWeight M q)) A := by simp [F] rw [← hzero] let l := nhdsWithin (0 : ℝ) (Set.Ioi 0) have : l.NeBot := nhdsWithin_Ioi_neBot (le_refl (0 : ℝ)) apply onePositive_of_tendsto (l := l) F (F 0) · intro i j have hc : Continuous (fun t => F t i j) := by dsimp [F, faceHessian] by_cases hij : i = j · simp only [ite_eq_left hij]; exact continuous_const · simp only [ite_eq_right hij] exact continuous_coeffDerivs_perturb ds (rankWeight M q) _ exact hc.continuousAt.tendsto.mono_left nhdsWithin_le_nhds · exact fun t => faceHessian_symm _ A · have hpos : ∀ᶠ t in l, 0 < t := self_mem_nhdsWithin filter_upwards [hpos] with t ht apply (rankWeight_positive_directions M hE q hq hq1 _ _).2 A intro b hb i obtain ⟨a,ha,rfl⟩ := List.mem_map.mp hb exact add_pos_of_nonneg_of_pos (hds a ha i) ht lemma onePositive_matrix_substitution {κ : Type*} [Fintype κ] [DecidableEq κ] (B : Matrix ι ι ℝ) (hB : OnePositive B.toBilin') (L : Matrix ι κ ℝ) : OnePositive (L.transpose * B * L).toBilin' := by rw [← Matrix.toBilin'_comp] intro e he v hv exact hB (L.toLin' e) he (L.toLin' v) hv noncomputable def slotDirection (E : Finset ι) (i : ι) : ℝ := if i ∈ E then 1 else 0 omit sectionInstance12 in lemma slotDirection_nonneg [Fintype ι] (E : Finset ι) (i : ι) : 0 ≤ slotDirection E i := by unfold slotDirection split_ifs <;> norm_num lemma coeffDeriv_slot (E : Finset ι) (f : Set ι → ℝ) (A : Set ι) : coeffDeriv (slotDirection E) f A = ∑ i ∈ E, if i ∈ A then 0 else f (insert i A) := by classical unfold coeffDeriv slotDirection rw [← Finset.sum_subset (Finset.subset_univ E)] · apply Finset.sum_congr rfl intro i hi simp [hi] · intro i _ hi simp [hi] lemma coeffDeriv_pair (a b : ι) (hab : a ≠ b) (f : Set ι → ℝ) (A : Set ι) (ha : a ∉ A) (hb : b ∉ A) : coeffDeriv (slotDirection {a,b}) f A = f (insert a A) + f (insert b A) := by rw [coeffDeriv_slot] simp [hab, ha, hb] theorem matroid_slot_signature {κ : Type*} [Fintype κ] [DecidableEq κ] (M : Matroid ι) (hE : M.E = Set.univ) (q : ℝ) (hq : 0 < q) (hq1 : q ≤ 1) (slots : List (Finset ι)) (A : Set ι) (L : Matrix {i // i ∉ A} κ ℝ) : OnePositive (L.transpose * faceHessian (coeffDerivs (slots.map slotDirection) (rankWeight M q)) A * L).toBilin' := by apply onePositive_matrix_substitution apply rankWeight_nonnegative_directions M hE q hq hq1 intro a ha i obtain ⟨E,_,rfl⟩ := List.mem_map.mp ha exact slotDirection_nonneg E i omit sectionInstance12 sectionInstance13 in lemma onePositive_smul [Fintype ι] [DecidableEq ι] (B : LinearMap.BilinForm ℝ (ι → ℝ)) (hB : OnePositive B) (c : ℝ) (hc : 0 < c) : OnePositive (c • B) := by intro e he v hv change 0 < c * B e e at he change c * B v e = 0 at hv change c * B v v ≤ 0 have he' : 0 < B e e := (mul_pos_iff_of_pos_left hc).mp he have hv' : B v e = 0 := (mul_eq_zero.mp hv).resolve_left (ne_of_gt hc) exact mul_nonpos_of_nonneg_of_nonpos hc.le (hB e he' v hv') lemma onePositive_submatrix {κ : Type*} [Fintype κ] [DecidableEq κ] (B : Matrix ι ι ℝ) (hB : OnePositive B.toBilin') (e : κ → ι) : OnePositive (B.submatrix e e).toBilin' := by classical let L : Matrix ι κ ℝ := fun i j => if i = e j then 1 else 0 have heq : L.transpose * B * L = B.submatrix e e := by ext i j change (∑ k, (∑ l, (if l = e i then (1 : ℝ) else 0) * B l k) * (if k = e j then (1 : ℝ) else 0)) = B (e i) (e j) simp rw [← heq] exact onePositive_matrix_substitution B hB L end DerivativeClosure theorem quadratic_split_bound (B : LinearMap.BilinForm ℝ V) (hB : OnePositive B) (hsymm : B.IsSymm) (e h d : V) (u X : ℝ) (hu : 0 < u) (hee : 0 < B e e) (hhe : B h e = 0) (hde : B d e = 0) (hhd : B h d = -2 * X) (hdd : B d d = -2 * u) : 2 * X ^ 2 / u ≤ -B h h := by have hor : B (h - (X / u) • d) e = 0 := by simp [map_sub, map_smul, hhe, hde] have hn := hB e hee (h - (X / u) • d) hor have hdh : B d h = -2 * X := by rw [hsymm.eq d h, hhd] simp only [map_sub, map_smul, LinearMap.sub_apply, LinearMap.smul_apply, smul_eq_mul, hhd, hdh, hdd] at hn have hu0 : u ≠ 0 := ne_of_gt hu field_simp at hn ⊢ nlinarith section MatrixSplit open scoped BigOperators variable {ι : Type*} [Fintype ι] [sectionInstance15 : DecidableEq ι] def splitMatrix (V : Matrix ι ι ℝ) (sa sb : ι → ℝ) (u : ℝ) : Matrix (ι ⊕ Bool) (ι ⊕ Bool) ℝ | .inl i, .inl j => V i j | .inl i, .inr false => sb i | .inl i, .inr true => sa i | .inr false, .inl i => sb i | .inr true, .inl i => sa i | .inr a, .inr b => if a = b then 0 else u def oldVector (h : ι → ℝ) : (ι ⊕ Bool) → ℝ | .inl i => h i | .inr _ => 0 def splitPositive : (ι ⊕ Bool) → ℝ | .inl _ => 0 | .inr _ => 1 def splitDifference : (ι ⊕ Bool) → ℝ | .inl _ => 0 | .inr false => 1 | .inr true => -1 theorem splitMatrix_symm (V : Matrix ι ι ℝ) (sa sb : ι → ℝ) (u : ℝ) (hV : ∀ i j, V i j = V j i) : (splitMatrix V sa sb u).toBilin'.IsSymm := by apply matrix_bilin_symm intro i j cases i with | inl i => cases j with | inl j => exact hV i j | inr b => cases b <;> rfl | inr a => cases a <;> cases j with | inl j => rfl | inr b => cases b <;> rfl theorem split_bound (V : Matrix ι ι ℝ) (sa sb h : ι → ℝ) (u : ℝ) (hu : 0 < u) (hV : ∀ i j, V i j = V j i) (hA : OnePositive (splitMatrix V sa sb u).toBilin') (hbal : ∑ i, (sa i + sb i) * h i = 0) : 2 * (∑ i, h i * sa i)^2 / u ≤ - V.toBilin' h h := by have bal : (∑ i, h i * sb i) = -(∑ i, h i * sa i) := by simp_rw [add_mul, Finset.sum_add_distrib] at hbal have hs : ∀ f : ι → ℝ, (∑ i, f i * h i) = ∑ i, h i * f i := by intro f apply Finset.sum_congr rfl intro i _ ring rw [hs sa, hs sb] at hbal linarith have hh : (splitMatrix V sa sb u).toBilin' (oldVector h) (oldVector h) = V.toBilin' h h := by simp [Matrix.toBilin'_apply, Fintype.sum_sum_type, splitMatrix, oldVector] rw [← hh] apply quadratic_split_bound (splitMatrix V sa sb u).toBilin' hA (splitMatrix_symm V sa sb u hV) splitPositive (oldVector h) splitDifference u (∑ i, h i * sa i) hu · simpa [Matrix.toBilin'_apply, Fintype.sum_sum_type, Fintype.sum_bool, splitMatrix, splitPositive] using (show 0 < u + u by linarith) · simp [Matrix.toBilin'_apply, Fintype.sum_sum_type, splitMatrix, splitPositive, oldVector, Finset.sum_add_distrib, bal] · simp [Matrix.toBilin'_apply, Fintype.sum_sum_type, splitMatrix, splitPositive, splitDifference] · simp [Matrix.toBilin'_apply, Fintype.sum_sum_type, splitMatrix, splitDifference, oldVector, Finset.sum_add_distrib, bal] ring · simp [Matrix.toBilin'_apply, Fintype.sum_sum_type, splitMatrix, splitDifference] ring def futureChild (V : Matrix ι ι ℝ) (c : ι → ℝ) : Matrix (Option ι) (Option ι) ℝ | some i, some j => V i j | some i, none => c i | none, some j => c j | none, none => 0 def extendVector (h : ι → ℝ) (a : ℝ) : Option ι → ℝ | some i => h i | none => a theorem future_conservation (Va Vb : Matrix ι ι ℝ) (c h : ι → ℝ) (a : ℝ) : (futureChild Va c).toBilin' (extendVector h a) (extendVector h a) + (futureChild Vb c).toBilin' (extendVector h (-a)) (extendVector h (-a)) = (Va + Vb).toBilin' h h := by simp only [Matrix.toBilin'_apply, Fintype.sum_option, futureChild, extendVector, mul_zero, zero_mul, Matrix.add_apply, mul_add, add_mul, Finset.sum_add_distrib, mul_neg, neg_mul, Finset.sum_neg_distrib] ring omit sectionInstance15 in theorem child_balance [DecidableEq ι] (s h : ι → ℝ) (u : ℝ) (hu : u ≠ 0) : ∑ i : Option ι, extendVector s u i * extendVector h (-(∑ j, h j * s j) / u) i = 0 := by simp only [Fintype.sum_option, extendVector] have hcomm : (∑ j, s j * h j) = ∑ j, h j * s j := by apply Finset.sum_congr rfl intro i _ ring rw [hcomm] field_simp ring omit sectionInstance15 in theorem demand_conservation [DecidableEq ι] (ga gb h : ι → ℝ) (g a : ℝ) : (∑ i : Option ι, extendVector h a i * extendVector ga g i) + (∑ i : Option ι, extendVector h (-a) i * extendVector gb g i) = ∑ i, h i * (ga i + gb i) := by simp only [Fintype.sum_option, extendVector, mul_add, neg_mul, Finset.sum_add_distrib] ring omit sectionInstance15 in theorem potential_increment [DecidableEq ι] (sa sb h W : ι → ℝ) (u wt X : ℝ) (hu : u ≠ 0) (hw : wt ≠ 0) : (∑ i : Option ι, extendVector sa u i * (extendVector h (-X/u) i)^2 / extendVector W wt i) + (∑ i : Option ι, extendVector sb u i * (extendVector h (X/u) i)^2 / extendVector W wt i) = (∑ i, (sa i + sb i) * (h i)^2 / W i) + 2*X^2/(u*wt) := by simp only [Fintype.sum_option, extendVector, add_mul, add_div, Finset.sum_add_distrib] field_simp ring omit sectionInstance15 in theorem leaf_clique_bound [DecidableEq ι] (s W h H : ι → ℝ) (hub : ι) (hs : ∀ i, 0 < s i) (hW : ∀ i, 0 < W i) (hbal : ∑ i, s i * h i = 0) : 2 * (∑ i, s i * h i * H i) ≤ (∑ i, s i * (h i)^2 / W i) + ∑ i, W i * s i * (H i - H hub)^2 := by have hterm : ∀ i, 2*(s i*h i*(H i-H hub)) ≤ s i*(h i)^2/W i + W i*s i*(H i-H hub)^2 := by intro i have hsq := mul_nonneg (div_nonneg (le_of_lt (hs i)) (le_of_lt (hW i))) (sq_nonneg (h i-W i*(H i-H hub))) have heq : s i*(h i)^2/W i + W i*s i*(H i-H hub)^2 - 2*(s i*h i*(H i-H hub)) = (s i/W i)*(h i-W i*(H i-H hub))^2 := by field_simp [ne_of_gt (hW i)] ; ring linarith have hsum := Finset.sum_le_sum (s := Finset.univ) (fun i _ => hterm i) have hz : (∑ i, s i * h i * H hub) = 0 := by rw [← Finset.sum_mul, hbal, zero_mul] simpa only [mul_sub, Finset.sum_sub_distrib, Finset.sum_add_distrib, ← Finset.mul_sum, hz, mul_zero, sub_zero] using hsum end MatrixSplit section RecursiveTransport open scoped BigOperators Classical Matrix variable {Γ : Type*} [sectionInstance16 : Fintype Γ] [sectionInstance17 : DecidableEq Γ] noncomputable def pairDirection (p : Γ × Γ) : Γ → ℝ := slotDirection {p.1,p.2} noncomputable def slotTotal (ps : List (Γ × Γ)) (f : Set Γ → ℝ) : Set Γ → ℝ := coeffDerivs (ps.map pairDirection) f lemma slotTotal_nil (f : Set Γ → ℝ) (A : Set Γ) : slotTotal [] f A = f A := rfl lemma slotTotal_cons (p : Γ × Γ) (ps : List (Γ × Γ)) (f : Set Γ → ℝ) (A : Set Γ) (hp : p.1 ≠ p.2) (ha : p.1 ∉ A) (hb : p.2 ∉ A) : slotTotal (p::ps) f A = slotTotal ps f (insert p.1 A) + slotTotal ps f (insert p.2 A) := by exact coeffDeriv_pair p.1 p.2 hp (slotTotal ps f) A ha hb def SlotsFresh : List (Γ × Γ) → Set Γ → Prop | [], _ => True | p::ps, B => p.1 ≠ p.2 ∧ p.1 ∉ B ∧ p.2 ∉ B ∧ SlotsFresh ps (insert p.1 (insert p.2 B)) omit sectionInstance16 sectionInstance17 in lemma SlotsFresh.mono [Fintype Γ] [DecidableEq Γ] {ps : List (Γ × Γ)} {A B : Set Γ} (h : SlotsFresh ps B) (hAB : A ⊆ B) : SlotsFresh ps A := by induction ps generalizing A B with | nil => trivial | cons p ps ih => obtain ⟨hp,ha,hb,ht⟩ := h exact ⟨hp, fun hx => ha (hAB hx), fun hx => hb (hAB hx), ih ht (Set.insert_subset_insert (Set.insert_subset_insert hAB))⟩ lemma slotTotal_pos (ps : List (Γ × Γ)) (f : Set Γ → ℝ) (hf : ∀ A, 0 < f A) (A : Set Γ) (hps : SlotsFresh ps A) : 0 < slotTotal ps f A := by induction ps generalizing A with | nil => exact hf A | cons p ps ih => obtain ⟨hp,ha,hb,ht⟩ := hps rw [slotTotal_cons p ps f A hp ha hb] apply add_pos · apply ih _ (ht.mono _) intro x hx rcases hx with rfl | hx · exact Set.mem_insert _ _ · exact Set.mem_insert_of_mem _ (Set.mem_insert_of_mem _ hx) · apply ih _ (ht.mono _) intro x hx exact Set.mem_insert_of_mem _ hx def appendPoint {ι : Type*} (e : ι → Γ) (a : Γ) : Option ι → Γ | none => a | some i => e i omit sectionInstance16 sectionInstance17 in lemma range_appendPoint [Fintype Γ] [DecidableEq Γ] {ι : Type*} (e : ι → Γ) (a : Γ) : Set.range (appendPoint e a) = insert a (Set.range e) := by ext x constructor · rintro ⟨i,rfl⟩ cases i with | none => exact Or.inl rfl | some i => exact Or.inr ⟨i,rfl⟩ · rintro (rfl | ⟨i,rfl⟩) · exact ⟨none,rfl⟩ · exact ⟨some i,rfl⟩ omit sectionInstance16 sectionInstance17 in lemma appendPoint_injective [Fintype Γ] [DecidableEq Γ] {ι : Type*} (e : ι → Γ) (a : Γ) (he : Function.Injective e) (ha : a ∉ Set.range e) : Function.Injective (appendPoint e a) := by intro i j h cases i <;> cases j · rfl · exact False.elim (ha ⟨_,h.symm⟩) · exact False.elim (ha ⟨_,h⟩) · exact congrArg some (he h) lemma slotsFresh_child {ι : Type*} (e : ι → Γ) (A : Set Γ) (p : Γ × Γ) (ps : List (Γ × Γ)) (h : SlotsFresh (p::ps) (A ∪ Set.range e)) : SlotsFresh ps (insert p.2 A ∪ Set.range (appendPoint e p.1)) ∧ SlotsFresh ps (insert p.1 A ∪ Set.range (appendPoint e p.2)) := by obtain ⟨_,_,_,ht⟩ := h rw [range_appendPoint, range_appendPoint] constructor · convert ht using 1 ; ext x ; simp ; tauto · convert ht using 1 ; ext x ; simp ; tauto omit sectionInstance16 sectionInstance17 in lemma appendPoint_fresh [Fintype Γ] [DecidableEq Γ] {ι : Type*} (e : ι → Γ) (A : Set Γ) (a b : Γ) (he : ∀ i, e i ∉ A) (hab : a ≠ b) (ha : a ∉ A) (hb : b ∉ Set.range e) : ∀ i, appendPoint e a i ∉ insert b A := by intro i cases i with | none => exact fun h => h.elim hab ha | some i => intro h rcases h with h | h · exact hb ⟨i,h⟩ · exact he i h noncomputable def pairMatrix {ι : Type*} [DecidableEq ι] (f : Set Γ → ℝ) (A : Set Γ) (e : ι → Γ) : Matrix ι ι ℝ := fun i j => if i = j then 0 else f (insert (e i) (insert (e j) A)) omit sectionInstance16 sectionInstance17 in lemma pairMatrix_symm [Fintype Γ] [DecidableEq Γ] {ι : Type*} [DecidableEq ι] (f : Set Γ → ℝ) (A : Set Γ) (e : ι → Γ) : ∀ i j, pairMatrix f A e i j = pairMatrix f A e j i := by intro i j by_cases hij : i = j · subst j; rfl · simp only [pairMatrix, hij, Ne.symm hij, ite_false, Set.insert_comm] def HasSlotSignature (f : Set Γ → ℝ) : Prop := ∀ (ps : List (Γ × Γ)) (A : Set Γ), OnePositive (faceHessian (slotTotal ps f) A).toBilin' lemma rankWeight_hasSlotSignature (M : Matroid Γ) (hE : M.E = Set.univ) (q : ℝ) (hq : 0 < q) (hq1 : q ≤ 1) : HasSlotSignature (rankWeight M q) := by intro ps A apply rankWeight_nonnegative_directions M hE q hq hq1 intro a ha i obtain ⟨p,_,rfl⟩ := List.mem_map.mp ha exact slotDirection_nonneg _ i lemma pairMatrix_signature {ι : Type*} [Fintype ι] [DecidableEq ι] (f : Set Γ → ℝ) (hSig : HasSlotSignature f) (ps : List (Γ × Γ)) (A : Set Γ) (e : ι → Γ) (he : Function.Injective e) (heA : ∀ i, e i ∉ A) : OnePositive (pairMatrix (slotTotal ps f) A e).toBilin' := by let e' : ι → {i // i ∉ A} := fun i => ⟨e i,heA i⟩ have hEq : pairMatrix (slotTotal ps f) A e = (faceHessian (slotTotal ps f) A).submatrix e' e' := by ext i j by_cases hij : i = j · subst j; simp [pairMatrix,faceHessian] · have hne : e' i ≠ e' j := fun h => hij (he (congrArg Subtype.val h)) simp only [pairMatrix, hij, ite_false, Matrix.submatrix_apply, faceHessian, hne] congr 1 ext x simp [e'] rw [hEq] exact onePositive_submatrix _ (hSig ps A) e' section Clique variable {ι : Type*} [Fintype ι] [sectionInstance19 : DecidableEq ι] lemma star_le_half_clique (E : ι → ι → ℝ) (hE : ∀ i j, 0 ≤ E i j) (hS : ∀ i j, E i j = E j i) (hD : ∀ i, E i i = 0) (hub : ι) : (∑ i, E i hub) ≤ (∑ i, ∑ j, E i j) / 2 := by have hrest : (∑ i ∈ Finset.univ.erase hub, E i hub) ≤ ∑ i ∈ Finset.univ.erase hub, ∑ j, E i j := by apply Finset.sum_le_sum intro i _ exact Finset.single_le_sum (fun j _ => hE i j) (Finset.mem_univ hub) rw [Finset.sum_erase (f := fun i => E i hub) _ (hD hub)] at hrest have ht := Finset.sum_erase_add Finset.univ (fun i => ∑ j, E i j) (Finset.mem_univ hub) have hrow : (∑ j, E hub j) = ∑ j, E j hub := by simp_rw [hS hub] rw [hrow] at ht linarith noncomputable def cliqueEnergy (s W H : ι → ℝ) : ℝ := (∑ i, ∑ j, min (W i*s i) (W j*s j) * (H i-H j)^2) / 2 omit sectionInstance19 in lemma cliqueEnergy_nonneg [DecidableEq ι] (s W H : ι → ℝ) (hs : ∀ i, 0 ≤ s i) (hW : ∀ i, 0 ≤ W i) : 0 ≤ cliqueEnergy s W H := by unfold cliqueEnergy apply div_nonneg _ (by norm_num) apply Finset.sum_nonneg intro i _ apply Finset.sum_nonneg intro j _ exact mul_nonneg (le_min (mul_nonneg (hW i) (hs i)) (mul_nonneg (hW j) (hs j))) (sq_nonneg _) lemma clique_linear_bound [Nonempty ι] (s W h H : ι → ℝ) (hs : ∀ i, 0 < s i) (hW : ∀ i, 0 < W i) (hbal : ∑ i, s i*h i = 0) : 2*(∑ i, s i*h i*H i) ≤ (∑ i, s i*(h i)^2/W i) + cliqueEnergy s W H := by obtain ⟨hub,_,hhub⟩ := Finset.exists_max_image Finset.univ (fun i => W i*s i) Finset.univ_nonempty have hl := leaf_clique_bound s W h H hub hs hW hbal have he := star_le_half_clique (fun i j => min (W i*s i) (W j*s j)*(H i-H j)^2) (fun i j => mul_nonneg (le_min (mul_pos (hW i) (hs i)).le (mul_pos (hW j) (hs j)).le) (sq_nonneg _)) (by intro i j; rw [min_comm]; ring) (by intro i; simp) hub simp_rw [min_eq_left (hhub _ (Finset.mem_univ _))] at he unfold cliqueEnergy linarith end Clique variable {ι : Type*} [sectionInstance20 : Fintype ι] [sectionInstance21 : DecidableEq ι] def splitEmbedding (e : ι → Γ) (a b : Γ) : (ι ⊕ Bool) → Γ | .inl i => e i | .inr false => a | .inr true => b omit sectionInstance16 sectionInstance17 sectionInstance20 sectionInstance21 in lemma splitEmbedding_injective [Fintype Γ] [DecidableEq Γ] [Fintype ι] [DecidableEq ι] (e : ι → Γ) (a b : Γ) (he : Function.Injective e) (hab : a ≠ b) (ha : a ∉ Set.range e) (hb : b ∉ Set.range e) : Function.Injective (splitEmbedding e a b) := by intro i j hij cases i with | inl i => cases j with | inl j => exact congrArg Sum.inl (he hij) | inr x => cases x with | false => exact False.elim (ha ⟨i,hij⟩) | true => exact False.elim (hb ⟨i,hij⟩) | inr x => cases j with | inl j => cases x with | false => exact False.elim (ha ⟨j,hij.symm⟩) | true => exact False.elim (hb ⟨j,hij.symm⟩) | inr y => cases x <;> cases y · rfl · exact False.elim (hab hij) · exact False.elim (hab hij.symm) · rfl omit sectionInstance16 sectionInstance17 sectionInstance20 in lemma pairMatrix_split [Fintype Γ] [DecidableEq Γ] [Fintype ι] (f : Set Γ → ℝ) (A : Set Γ) (e : ι → Γ) (a b : Γ) : pairMatrix f A (splitEmbedding e a b) = splitMatrix (pairMatrix f A e) (fun i => f (insert (e i) (insert b A))) (fun i => f (insert (e i) (insert a A))) (f (insert a (insert b A))) := by ext i j cases i with | inl i => cases j with | inl j => simp [pairMatrix, splitMatrix, splitEmbedding] | inr x => cases x <;> simp [pairMatrix, splitMatrix, splitEmbedding] | inr x => cases j with | inl j => cases x <;> simp [pairMatrix, splitMatrix, splitEmbedding, Set.insert_comm] | inr y => cases x <;> cases y <;> simp [pairMatrix, splitMatrix, splitEmbedding, Set.insert_comm] lemma slot_split_signature (f : Set Γ → ℝ) (hSig : HasSlotSignature f) (ps : List (Γ × Γ)) (A : Set Γ) (e : ι → Γ) (a b : Γ) (he : Function.Injective e) (heA : ∀ i, e i ∉ A) (hab : a ≠ b) (ha : a ∉ A ∪ Set.range e) (hb : b ∉ A ∪ Set.range e) : OnePositive (splitMatrix (pairMatrix (slotTotal ps f) A e) (fun i => slotTotal ps f (insert (e i) (insert b A))) (fun i => slotTotal ps f (insert (e i) (insert a A))) (slotTotal ps f (insert a (insert b A)))).toBilin' := by rw [← pairMatrix_split] apply pairMatrix_signature f hSig ps A _ (splitEmbedding_injective e a b he hab (fun h => ha (Or.inr h)) (fun h => hb (Or.inr h))) intro i cases i with | inl i => exact heA i | inr x => cases x with | false => exact fun h => ha (Or.inl h) | true => exact fun h => hb (Or.inl h) omit sectionInstance16 sectionInstance17 sectionInstance20 in lemma pairMatrix_append [Fintype Γ] [DecidableEq Γ] [Fintype ι] (f : Set Γ → ℝ) (A : Set Γ) (e : ι → Γ) (a b : Γ) : pairMatrix f (insert b A) (appendPoint e a) = futureChild (pairMatrix f (insert b A) e) (fun i => f (insert (e i) (insert a (insert b A)))) := by ext i j cases i <;> cases j <;> simp [pairMatrix, appendPoint, futureChild, Set.insert_comm] omit sectionInstance20 sectionInstance21 in lemma slotTotal_parent [Fintype ι] [DecidableEq ι] (ps : List (Γ × Γ)) (f : Set Γ → ℝ) (A : Set Γ) (e : ι → Γ) (p : Γ × Γ) (hp : p.1 ≠ p.2) (ha : p.1 ∉ A ∪ Set.range e) (hb : p.2 ∉ A ∪ Set.range e) : ∀ i, slotTotal (p::ps) f (insert (e i) A) = slotTotal ps f (insert (e i) (insert p.2 A)) + slotTotal ps f (insert (e i) (insert p.1 A)) := by intro i rw [slotTotal_cons p ps f _ hp] · rw [Set.insert_comm p.1, Set.insert_comm p.2, add_comm] · intro h exact h.elim (fun h => ha (Or.inr ⟨i,h.symm⟩)) (fun h => ha (Or.inl h)) · intro h exact h.elim (fun h => hb (Or.inr ⟨i,h.symm⟩)) (fun h => hb (Or.inl h)) omit sectionInstance20 in lemma pairMatrix_parent [Fintype ι] (ps : List (Γ × Γ)) (f : Set Γ → ℝ) (A : Set Γ) (e : ι → Γ) (p : Γ × Γ) (hp : p.1 ≠ p.2) (ha : p.1 ∉ A ∪ Set.range e) (hb : p.2 ∉ A ∪ Set.range e) : pairMatrix (slotTotal (p::ps) f) A e = pairMatrix (slotTotal ps f) (insert p.2 A) e + pairMatrix (slotTotal ps f) (insert p.1 A) e := by ext i j by_cases hij : i = j · subst j; simp [pairMatrix] simp only [pairMatrix, hij, ite_false, Matrix.add_apply] rw [slotTotal_cons p ps f _ hp] · rw [Set.insert_comm p.1 (e i), Set.insert_comm p.1 (e j), Set.insert_comm p.2 (e i), Set.insert_comm p.2 (e j), add_comm] · intro h rcases h with h | h | h · exact ha (Or.inr ⟨i,h.symm⟩) · exact ha (Or.inr ⟨j,h.symm⟩) · exact ha (Or.inl h) · intro h rcases h with h | h | h · exact hb (Or.inr ⟨i,h.symm⟩) · exact hb (Or.inr ⟨j,h.symm⟩) · exact hb (Or.inl h) lemma slot_future_conservation (ps : List (Γ × Γ)) (f : Set Γ → ℝ) (A : Set Γ) (e : ι → Γ) (p : Γ × Γ) (h : ι → ℝ) (c : ℝ) (hp : p.1 ≠ p.2) (ha : p.1 ∉ A ∪ Set.range e) (hb : p.2 ∉ A ∪ Set.range e) : (pairMatrix (slotTotal ps f) (insert p.2 A) (appendPoint e p.1)).toBilin' (extendVector h c) (extendVector h c) + (pairMatrix (slotTotal ps f) (insert p.1 A) (appendPoint e p.2)).toBilin' (extendVector h (-c)) (extendVector h (-c)) = (pairMatrix (slotTotal (p::ps) f) A e).toBilin' h h := by rw [pairMatrix_append, pairMatrix_append, pairMatrix_parent ps f A e p hp ha hb] have heq : (fun i => slotTotal ps f (insert (e i) (insert p.2 (insert p.1 A)))) = (fun i => slotTotal ps f (insert (e i) (insert p.1 (insert p.2 A)))) := by simp only [Set.insert_comm p.2 p.1] rw [heq] exact future_conservation _ _ _ h c noncomputable def transportDemand (ps : List (Γ × Γ)) (f H : Set Γ → ℝ) (A : Set Γ) (e : ι → Γ) (h : ι → ℝ) : ℝ := ∑ i, h i * slotTotal ps (fun S => f S*H S) (insert (e i) A) noncomputable def transportPotential (ps : List (Γ × Γ)) (f : Set Γ → ℝ) (A : Set Γ) (e : ι → Γ) (h : ι → ℝ) (W : Γ → ℝ) : ℝ := ∑ i, slotTotal ps f (insert (e i) A) * (h i)^2 / W (e i) def slotPunctures : List (Γ × Γ) → List ((Γ × Γ) × List (Γ × Γ)) | [] => [] | p::ps => (p,ps) :: (slotPunctures ps).map (fun x => (x.1,p::x.2)) noncomputable def transportCorrection (ps : List (Γ × Γ)) (f : Set Γ → ℝ) (A : Set Γ) (e : ι → Γ) (h : ι → ℝ) (W : Γ → ℝ) : ℝ := ((slotPunctures ps).map (fun x => (pairMatrix (slotTotal x.2 f) A e).toBilin' h h / W x.1.1)).sum noncomputable def transportEnergy {ι : Type*} [Fintype ι] (ps : List (Γ × Γ)) (f H : Set Γ → ℝ) (A : Set Γ) (e : ι → Γ) (W : Γ → ℝ) : ℝ := match ps with | [] => cliqueEnergy (fun i => f (insert (e i) A)) (fun i => W (e i)) (fun i => H (insert (e i) A)) | p::ps => transportEnergy ps f H (insert p.2 A) (appendPoint e p.1) W + transportEnergy ps f H (insert p.1 A) (appendPoint e p.2) W termination_by ps.length omit sectionInstance16 sectionInstance17 in lemma transportEnergy_nil [Fintype Γ] [DecidableEq Γ] {ι : Type*} [Fintype ι] (f H : Set Γ → ℝ) (A : Set Γ) (e : ι → Γ) (W : Γ → ℝ) : transportEnergy [] f H A e W = cliqueEnergy (fun i => f (insert (e i) A)) (fun i => W (e i)) (fun i => H (insert (e i) A)) := by rw [transportEnergy] omit sectionInstance16 sectionInstance17 in lemma transportEnergy_cons [Fintype Γ] [DecidableEq Γ] {ι : Type*} [Fintype ι] (p : Γ × Γ) (ps : List (Γ × Γ)) (f H : Set Γ → ℝ) (A : Set Γ) (e : ι → Γ) (W : Γ → ℝ) : transportEnergy (p::ps) f H A e W = transportEnergy ps f H (insert p.2 A) (appendPoint e p.1) W + transportEnergy ps f H (insert p.1 A) (appendPoint e p.2) W := by rw [transportEnergy] lemma transportDemand_split (ps : List (Γ × Γ)) (f H : Set Γ → ℝ) (A : Set Γ) (e : ι → Γ) (p : Γ × Γ) (h : ι → ℝ) (c : ℝ) (hp : p.1 ≠ p.2) (ha : p.1 ∉ A ∪ Set.range e) (hb : p.2 ∉ A ∪ Set.range e) : transportDemand ps f H (insert p.2 A) (appendPoint e p.1) (extendVector h c) + transportDemand ps f H (insert p.1 A) (appendPoint e p.2) (extendVector h (-c)) = transportDemand (p::ps) f H A e h := by unfold transportDemand simp only [Fintype.sum_option, extendVector, appendPoint] rw [Set.insert_comm p.2 p.1] simp_rw [slotTotal_parent ps (fun S => f S*H S) A e p hp ha hb] simp only [mul_add, Finset.sum_add_distrib, neg_mul] ring lemma transportCorrection_split (ps : List (Γ × Γ)) (f : Set Γ → ℝ) (A : Set Γ) (e : ι → Γ) (p : Γ × Γ) (h : ι → ℝ) (c : ℝ) (W : Γ → ℝ) (hp : p.1 ≠ p.2) (ha : p.1 ∉ A ∪ Set.range e) (hb : p.2 ∉ A ∪ Set.range e) : transportCorrection (p::ps) f A e h W = (pairMatrix (slotTotal ps f) A e).toBilin' h h / W p.1 + (transportCorrection ps f (insert p.2 A) (appendPoint e p.1) (extendVector h c) W + transportCorrection ps f (insert p.1 A) (appendPoint e p.2) (extendVector h (-c)) W) := by simp only [transportCorrection, slotPunctures, List.map_cons, List.map_map, List.sum_cons] rw [← List.sum_map_add] congr 1 apply congrArg List.sum apply List.map_congr_left intro x _ dsimp rw [← add_div, slot_future_conservation x.2 f A e p h c hp ha hb] lemma transportPotential_split (ps : List (Γ × Γ)) (f : Set Γ → ℝ) (A : Set Γ) (e : ι → Γ) (p : Γ × Γ) (h : ι → ℝ) (X u : ℝ) (W : Γ → ℝ) (hp : p.1 ≠ p.2) (ha : p.1 ∉ A ∪ Set.range e) (hb : p.2 ∉ A ∪ Set.range e) (hu : u = slotTotal ps f (insert p.1 (insert p.2 A))) (hu0 : u ≠ 0) (hw : W p.1 = W p.2) (hw0 : W p.1 ≠ 0) : transportPotential ps f (insert p.2 A) (appendPoint e p.1) (extendVector h (-X/u)) W + transportPotential ps f (insert p.1 A) (appendPoint e p.2) (extendVector h (X/u)) W = transportPotential (p::ps) f A e h W + 2*X^2/(u*W p.1) := by unfold transportPotential simp only [Fintype.sum_option, extendVector, appendPoint] rw [Set.insert_comm p.2 p.1, ← hu, ← hw] simp_rw [slotTotal_parent ps f A e p hp ha hb] simp only [add_mul, add_div, Finset.sum_add_distrib] field_simp ring theorem transport_linear_bound (ps : List (Γ × Γ)) : ∀ {κ : Type*} [Fintype κ] [DecidableEq κ] [Nonempty κ] (f H : Set Γ → ℝ) (A : Set Γ) (e : κ → Γ) (h : κ → ℝ) (W : Γ → ℝ), (∀ S, 0 < f S) → HasSlotSignature f → Function.Injective e → (∀ i, e i ∉ A) → SlotsFresh ps (A ∪ Set.range e) → (∀ i, 0 < W i) → (∀ p ∈ ps, W p.1 = W p.2) → (∑ i, slotTotal ps f (insert (e i) A)*h i = 0) → 2*transportDemand ps f H A e h ≤ transportPotential ps f A e h W - transportCorrection ps f A e h W + transportEnergy ps f H A e W := by induction ps with | nil => intro κ _ _ _ f H A e h W hf _ _ _ _ hW _ hbal have hb : ∑ i, f (insert (e i) A)*h i = 0 := hbal have hl := clique_linear_bound (fun i => f (insert (e i) A)) (fun i => W (e i)) h (fun i => H (insert (e i) A)) (fun i => hf _) (fun i => hW _) hb simpa [transportDemand, transportPotential, transportCorrection, slotPunctures, slotTotal, coeffDerivs, transportEnergy_nil, mul_comm, mul_left_comm, mul_assoc] using hl | cons p ps ih => intro κ _ _ _ f H A e h W hf hSig he heA hFresh hW hw hbal obtain ⟨hab,ha,hb,ht⟩ := hFresh have hFresh' : SlotsFresh (p::ps) (A ∪ Set.range e) := ⟨hab,ha,hb,ht⟩ obtain ⟨hfa,hfb⟩ := slotsFresh_child e A p ps hFresh' let sa : κ → ℝ := fun i => slotTotal ps f (insert (e i) (insert p.2 A)) let sb : κ → ℝ := fun i => slotTotal ps f (insert (e i) (insert p.1 A)) let u : ℝ := slotTotal ps f (insert p.1 (insert p.2 A)) let X : ℝ := ∑ i, h i*sa i let c : ℝ := -X/u have hu : 0 < u := slotTotal_pos ps f hf _ (ht.mono (Set.insert_subset_insert (Set.insert_subset_insert Set.subset_union_left))) have hb0 : (∑ i, (sa i+sb i)*h i) = 0 := by simpa only [slotTotal_parent ps f A e p hab ha hb] using hbal have hXb : (∑ i, h i*sb i) = -X := by simp only [add_mul, Finset.sum_add_distrib] at hb0 have ha' : (∑ i, sa i*h i) = X := by dsimp [X]; apply Finset.sum_congr rfl; intro i _; ring have hb' : (∑ i, sb i*h i) = ∑ i, h i*sb i := by apply Finset.sum_congr rfl; intro i _; ring rw [ha',hb'] at hb0 linarith have hcB : -c = -(∑ i, h i*sb i)/u := by rw [hXb]; dsimp [c]; ring have hba : ∑ i, slotTotal ps f (insert (appendPoint e p.1 i) (insert p.2 A)) * extendVector h c i = 0 := by have hc := child_balance sa h u (ne_of_gt hu) simp only [Fintype.sum_option, extendVector] at hc simpa only [Fintype.sum_option, extendVector, appendPoint, sa, u, c, X] using hc have hbb : ∑ i, slotTotal ps f (insert (appendPoint e p.2 i) (insert p.1 A)) * extendVector h (-c) i = 0 := by rw [hcB] have hc := child_balance sb h u (ne_of_gt hu) simp only [Fintype.sum_option, extendVector] at hc simpa only [Fintype.sum_option, extendVector, appendPoint, u, sb, Set.insert_comm p.2 p.1] using hc have hwa := hw p (List.mem_cons_self ..) have hwt : ∀ p ∈ ps, W p.1 = W p.2 := fun q hq => hw q (List.mem_cons_of_mem _ hq) have hla := ih f H (insert p.2 A) (appendPoint e p.1) (extendVector h c) W hf hSig (appendPoint_injective e p.1 he (fun h => ha (Or.inr h))) (appendPoint_fresh e A p.1 p.2 heA hab (fun h => ha (Or.inl h)) (fun h => hb (Or.inr h))) hfa hW hwt hba have hlb := ih f H (insert p.1 A) (appendPoint e p.2) (extendVector h (-c)) W hf hSig (appendPoint_injective e p.2 he (fun h => hb (Or.inr h))) (appendPoint_fresh e A p.2 p.1 heA hab.symm (fun h => hb (Or.inl h)) (fun h => ha (Or.inr h))) hfb hW hwt hbb have hsplit := split_bound (pairMatrix (slotTotal ps f) A e) sa sb h u hu (pairMatrix_symm _ A e) (slot_split_signature f hSig ps A e p.1 p.2 he heA hab ha hb) hb0 have hcost : 2*X^2/(u*W p.1) ≤ -(pairMatrix (slotTotal ps f) A e).toBilin' h h / W p.1 := by simpa only [X, div_div] using div_le_div_of_nonneg_right hsplit (hW p.1).le have hpot := transportPotential_split ps f A e p h X u W hab ha hb rfl (ne_of_gt hu) hwa (ne_of_gt (hW p.1)) have hcN : X/u = -c := by dsimp [c]; ring rw [hcN] at hpot change transportPotential ps f (insert p.2 A) (appendPoint e p.1) (extendVector h c) W + transportPotential ps f (insert p.1 A) (appendPoint e p.2) (extendVector h (-c)) W = _ at hpot rw [← transportDemand_split ps f H A e p h c hab ha hb, transportEnergy_cons, transportCorrection_split ps f A e p h c W hab ha hb] rw [neg_div] at hcost linarith end RecursiveTransport section TransportRoot open scoped BigOperators Classical Matrix variable {Γ ι : Type*} [sectionInstance22 : Fintype Γ] [sectionInstance23 : DecidableEq Γ] [Fintype ι] [sectionInstance25 : DecidableEq ι] omit sectionInstance25 in lemma transportDemand_smul [DecidableEq ι] (ps : List (Γ × Γ)) (f H : Set Γ → ℝ) (A : Set Γ) (e : ι → Γ) (h : ι → ℝ) (c : ℝ) : transportDemand ps f H A e (c • h) = c * transportDemand ps f H A e h := by simp [transportDemand, Pi.smul_apply, smul_eq_mul, mul_assoc, Finset.mul_sum] omit sectionInstance25 in lemma transportPotential_smul [DecidableEq ι] (ps : List (Γ × Γ)) (f : Set Γ → ℝ) (A : Set Γ) (e : ι → Γ) (h : ι → ℝ) (W : Γ → ℝ) (c : ℝ) : transportPotential ps f A e (c • h) W = c^2 * transportPotential ps f A e h W := by unfold transportPotential rw [Finset.mul_sum] apply Finset.sum_congr rfl intro i _ simp only [Pi.smul_apply, smul_eq_mul] ring lemma transportCorrection_smul (ps : List (Γ × Γ)) (f : Set Γ → ℝ) (A : Set Γ) (e : ι → Γ) (h : ι → ℝ) (W : Γ → ℝ) (c : ℝ) : transportCorrection ps f A e (c • h) W = c^2 * transportCorrection ps f A e h W := by unfold transportCorrection rw [← List.sum_map_mul_left] apply congrArg List.sum apply List.map_congr_left intro x _ simp only [map_smul, LinearMap.smul_apply, smul_eq_mul] ring lemma squared_le_of_linear_scalings (D C E : ℝ) (hC : 0 < C) (h : ∀ t : ℝ, 2*t*D ≤ t^2*C + E) : D^2 ≤ C*E := by have ht := h (D/C) have ht' := (mul_le_mul_of_nonneg_right ht hC.le) field_simp at ht' nlinarith theorem transport_squared_bound [Nonempty ι] (ps : List (Γ × Γ)) (f H : Set Γ → ℝ) (A : Set Γ) (e : ι → Γ) (h : ι → ℝ) (W : Γ → ℝ) (hf : ∀ S, 0 < f S) (hSig : HasSlotSignature f) (he : Function.Injective e) (heA : ∀ i, e i ∉ A) (hps : SlotsFresh ps (A ∪ Set.range e)) (hW : ∀ i, 0 < W i) (hw : ∀ p ∈ ps, W p.1 = W p.2) (hbal : ∑ i, slotTotal ps f (insert (e i) A)*h i = 0) (hC : 0 < transportPotential ps f A e h W - transportCorrection ps f A e h W) : (transportDemand ps f H A e h)^2 ≤ (transportPotential ps f A e h W - transportCorrection ps f A e h W) * transportEnergy ps f H A e W := by apply squared_le_of_linear_scalings _ _ _ hC intro t have hbal' : ∑ i, slotTotal ps f (insert (e i) A)*(t • h) i = 0 := by simp only [Pi.smul_apply, smul_eq_mul] simp_rw [mul_left_comm _ t, ← Finset.mul_sum, hbal, mul_zero] have ht := transport_linear_bound ps f H A e (t • h) W hf hSig he heA hps hW hw hbal' rw [transportDemand_smul,transportPotential_smul,transportCorrection_smul] at ht nlinarith lemma slotTotal_nonneg (ps : List (Γ × Γ)) (f : Set Γ → ℝ) (hf : ∀ S, 0 ≤ f S) (A : Set Γ) : 0 ≤ slotTotal ps f A := by induction ps generalizing A with | nil => exact hf A | cons p ps ih => change 0 ≤ coeffDeriv (pairDirection p) (slotTotal ps f) A apply Finset.sum_nonneg intro i _ split_ifs · exact le_rfl · exact mul_nonneg (slotDirection_nonneg _ i) (ih _) def rootEmbedding (p d : Γ) : Bool → Γ := fun b => if b then d else p omit sectionInstance22 sectionInstance23 in lemma rootEmbedding_injective [Fintype Γ] [DecidableEq Γ] (p d : Γ) (hpd : p ≠ d) : Function.Injective (rootEmbedding p d) := by intro i j h cases i <;> cases j <;> simp_all [rootEmbedding] noncomputable def rootDemand (sp sd : ℝ) : Bool → ℝ := fun b => if b then -(1/sd) else 1/sp noncomputable def rootCoefficient (ps : List (Γ × Γ)) (f : Set Γ → ℝ) (A : Set Γ) (p d : Γ) (W : Γ → ℝ) : ℝ := let sp := slotTotal ps f (insert p A) let sd := slotTotal ps f (insert d A) 1/(sp*W p) + 1/(sd*W d) + 2/(sp*sd)* ((slotPunctures ps).map (fun x => slotTotal x.2 f (insert p (insert d A))/W x.1.1)).sum lemma rootPotential (ps : List (Γ × Γ)) (f : Set Γ → ℝ) (A : Set Γ) (p d : Γ) (W : Γ → ℝ) (hsp : slotTotal ps f (insert p A) ≠ 0) (hsd : slotTotal ps f (insert d A) ≠ 0) : transportPotential ps f A (rootEmbedding p d) (rootDemand (slotTotal ps f (insert p A)) (slotTotal ps f (insert d A))) W = 1/(slotTotal ps f (insert p A)*W p) + 1/(slotTotal ps f (insert d A)*W d) := by simp only [transportPotential, Fintype.sum_bool, rootEmbedding, rootDemand, Bool.false_eq_true, ite_false, ite_true] field_simp ; ring lemma rootCorrection (ps : List (Γ × Γ)) (f : Set Γ → ℝ) (A : Set Γ) (p d : Γ) (W : Γ → ℝ) (sp sd : ℝ) : transportCorrection ps f A (rootEmbedding p d) (rootDemand sp sd) W = -(2/(sp*sd)*((slotPunctures ps).map (fun x => slotTotal x.2 f (insert p (insert d A))/W x.1.1)).sum) := by unfold transportCorrection rw [← neg_mul, ← List.sum_map_mul_left] apply congrArg List.sum apply List.map_congr_left intro x _ simp only [Matrix.toBilin'_apply, Fintype.sum_bool, pairMatrix, rootEmbedding, rootDemand, Bool.false_eq_true, Bool.true_eq_false, ite_false, ite_true, Set.insert_comm d p] ring lemma rootCoefficient_pos (ps : List (Γ × Γ)) (f : Set Γ → ℝ) (hf : ∀ S, 0 < f S) (A : Set Γ) (p d : Γ) (W : Γ → ℝ) (hps : SlotsFresh ps (A ∪ Set.range (rootEmbedding p d))) (hW : ∀ i, 0 < W i) : 0 < rootCoefficient ps f A p d W := by have hfp : SlotsFresh ps (insert p A) := hps.mono (by intro x hx rcases hx with rfl | hx · exact Or.inr ⟨false,rfl⟩ · exact Or.inl hx) have hfd : SlotsFresh ps (insert d A) := hps.mono (by intro x hx rcases hx with rfl | hx · exact Or.inr ⟨true,rfl⟩ · exact Or.inl hx) have hp := slotTotal_pos ps f hf _ hfp have hd := slotTotal_pos ps f hf _ hfd unfold rootCoefficient apply add_pos_of_pos_of_nonneg · exact add_pos (one_div_pos.mpr (mul_pos hp (hW p))) (one_div_pos.mpr (mul_pos hd (hW d))) · apply mul_nonneg (div_nonneg (by norm_num) (mul_pos hp hd).le) apply List.sum_nonneg intro x hx obtain ⟨y,_,rfl⟩ := List.mem_map.mp hx exact div_nonneg (slotTotal_nonneg _ f (fun S => (hf S).le) _) (hW _).le theorem transport_root_bound (ps : List (Γ × Γ)) (f H : Set Γ → ℝ) (A : Set Γ) (p d : Γ) (W : Γ → ℝ) (hf : ∀ S, 0 < f S) (hSig : HasSlotSignature f) (hpd : p ≠ d) (hpA : p ∉ A) (hdA : d ∉ A) (hps : SlotsFresh ps (A ∪ Set.range (rootEmbedding p d))) (hW : ∀ i, 0 < W i) (hw : ∀ p ∈ ps, W p.1 = W p.2) : (slotTotal ps (fun S => f S*H S) (insert p A) / slotTotal ps f (insert p A) - slotTotal ps (fun S => f S*H S) (insert d A) / slotTotal ps f (insert d A))^2 ≤ rootCoefficient ps f A p d W * transportEnergy ps f H A (rootEmbedding p d) W := by have heA : ∀ i, rootEmbedding p d i ∉ A := by intro i; cases i <;> assumption have hfresh : ∀ i, SlotsFresh ps (insert (rootEmbedding p d i) A) := by intro i apply hps.mono intro x hx rcases hx with rfl | hx · exact Or.inr ⟨i,rfl⟩ · exact Or.inl hx have hsp := slotTotal_pos ps f hf _ (hfresh false) have hsd := slotTotal_pos ps f hf _ (hfresh true) change 0 < slotTotal ps f (insert p A) at hsp change 0 < slotTotal ps f (insert d A) at hsd let h := rootDemand (slotTotal ps f (insert p A)) (slotTotal ps f (insert d A)) have hbal : ∑ i, slotTotal ps f (insert (rootEmbedding p d i) A)*h i = 0 := by simp [h,rootDemand,rootEmbedding, ne_of_gt hsp, ne_of_gt hsd] have hcoef : transportPotential ps f A (rootEmbedding p d) h W - transportCorrection ps f A (rootEmbedding p d) h W = rootCoefficient ps f A p d W := by dsimp [h] rw [rootPotential ps f A p d W (ne_of_gt hsp) (ne_of_gt hsd), rootCorrection] simp only [rootCoefficient, sub_neg_eq_add] have ht := transport_squared_bound ps f H A (rootEmbedding p d) h W hf hSig (rootEmbedding_injective p d hpd) heA hps hW hw hbal (by rw [hcoef]; exact rootCoefficient_pos ps f hf A p d W hps hW) rw [hcoef] at ht simpa [transportDemand,h,rootDemand,rootEmbedding,Fintype.sum_bool,div_eq_mul_inv, mul_comm,sub_eq_add_neg,add_comm] using ht end TransportRoot section TransportGraph open scoped BigOperators Classical variable {Γ : Type*} [sectionInstance26 : Fintype Γ] [sectionInstance27 : DecidableEq Γ] def ExchangeAdjacent (S T : Set Γ) : Prop := ∃ (A : Set Γ) (a b : Γ), a ≠ b ∧ a ∉ A ∧ b ∉ A ∧ S = insert a A ∧ T = insert b A noncomputable def slotVertices {ι : Type*} [Fintype ι] (ps : List (Γ × Γ)) (A : Set Γ) (e : ι → Γ) : Finset (Set Γ) := match ps with | [] => Finset.univ.image (fun i => insert (e i) A) | p::ps => slotVertices ps (insert p.2 A) (appendPoint e p.1) ∪ slotVertices ps (insert p.1 A) (appendPoint e p.2) termination_by ps.length noncomputable def transportEdges {ι : Type*} [Fintype ι] [DecidableEq ι] (ps : List (Γ × Γ)) (A : Set Γ) (e : ι → Γ) : Finset (Set Γ × Set Γ) := match ps with | [] => (Finset.univ.filter (fun ij : ι × ι => ij.1 ≠ ij.2)).image (fun ij => (insert (e ij.1) A, insert (e ij.2) A)) | p::ps => transportEdges ps (insert p.2 A) (appendPoint e p.1) ∪ transportEdges ps (insert p.1 A) (appendPoint e p.2) termination_by ps.length noncomputable def missingMultiplier {ι : Type*} [Fintype ι] (ps : List (Γ × Γ)) (e : ι → Γ) (W : Γ → ℝ) (S : Set Γ) : ℝ := (∑ i, if e i ∈ S then W (e i) else 0) + (ps.map (fun p => if p.1 ∈ S ∧ p.2 ∈ S then W p.1 else 0)).sum omit sectionInstance26 sectionInstance27 in lemma transportEdges_fixed [Fintype Γ] [DecidableEq Γ] (ps : List (Γ × Γ)) : ∀ {ι : Type*} [Fintype ι] [DecidableEq ι] (A : Set Γ) (e : ι → Γ) (ST : Set Γ × Set Γ), ST ∈ transportEdges ps A e → A ⊆ ST.1 ∩ ST.2 := by induction ps with | nil => intro ι _ _ A e ST h rw [transportEdges] at h obtain ⟨ij,_,rfl⟩ := Finset.mem_image.mp h exact Set.subset_inter (Set.subset_insert _ _) (Set.subset_insert _ _) | cons p ps ih => intro ι _ _ A e ST h rw [transportEdges] at h rcases Finset.mem_union.mp h with h | h · exact (Set.subset_insert p.2 A).trans (ih _ _ _ h) · exact (Set.subset_insert p.1 A).trans (ih _ _ _ h) lemma transportEdges_not_holes (ps : List (Γ × Γ)) : ∀ {ι : Type*} [Fintype ι] [DecidableEq ι] (A : Set Γ) (e : ι → Γ), Function.Injective e → (∀ i, e i ∉ A) → SlotsFresh ps (A ∪ Set.range e) → ∀ ST ∈ transportEdges ps A e, ∀ i, e i ∉ ST.1 ∩ ST.2 := by induction ps with | nil => intro ι _ _ A e he heA _ ST h i rw [transportEdges] at h obtain ⟨ij,hij,rfl⟩ := Finset.mem_image.mp h have hij' := (Finset.mem_filter.mp hij).2 intro ⟨hi,hj⟩ have hi' : e i = e ij.1 := hi.resolve_right (heA i) have hj' : e i = e ij.2 := hj.resolve_right (heA i) exact hij' ((he hi').symm.trans (he hj')) | cons p ps ih => intro ι _ _ A e he heA hps ST h i obtain ⟨hab,ha,hb,ht⟩ := hps have hps' : SlotsFresh (p::ps) (A ∪ Set.range e) := ⟨hab,ha,hb,ht⟩ obtain ⟨hfa,hfb⟩ := slotsFresh_child e A p ps hps' rw [transportEdges] at h rcases Finset.mem_union.mp h with h | h · exact ih (insert p.2 A) (appendPoint e p.1) (appendPoint_injective e p.1 he (fun h => ha (Or.inr h))) (appendPoint_fresh e A p.1 p.2 heA hab (fun h => ha (Or.inl h)) (fun h => hb (Or.inr h))) hfa ST h (some i) · exact ih (insert p.1 A) (appendPoint e p.2) (appendPoint_injective e p.2 he (fun h => hb (Or.inr h))) (appendPoint_fresh e A p.2 p.1 heA hab.symm (fun h => hb (Or.inl h)) (fun h => ha (Or.inr h))) hfb ST h (some i) lemma transportEdges_disjoint {ι : Type*} [Fintype ι] [DecidableEq ι] (ps : List (Γ × Γ)) (A : Set Γ) (e : ι → Γ) (p : Γ × Γ) (he : Function.Injective e) (heA : ∀ i, e i ∉ A) (hps : SlotsFresh (p::ps) (A ∪ Set.range e)) : Disjoint (transportEdges ps (insert p.2 A) (appendPoint e p.1)) (transportEdges ps (insert p.1 A) (appendPoint e p.2)) := by apply Finset.disjoint_left.mpr intro ST ha hb have hfix := transportEdges_fixed ps (insert p.2 A) (appendPoint e p.1) ST ha obtain ⟨hab,hpa,hpb,ht⟩ := hps have hps' : SlotsFresh (p::ps) (A ∪ Set.range e) := ⟨hab,hpa,hpb,ht⟩ have hn := transportEdges_not_holes ps (insert p.1 A) (appendPoint e p.2) (appendPoint_injective e p.2 he (fun h => hpb (Or.inr h))) (appendPoint_fresh e A p.2 p.1 heA hab.symm (fun h => hpb (Or.inl h)) (fun h => hpa (Or.inr h))) (slotsFresh_child e A p ps hps').2 ST hb none exact hn (hfix (Set.mem_insert _ _)) omit sectionInstance26 sectionInstance27 in lemma missingMultiplier_child_left [Fintype Γ] [DecidableEq Γ] {ι : Type*} [Fintype ι] (ps : List (Γ × Γ)) (p : Γ × Γ) (e : ι → Γ) (W : Γ → ℝ) (S : Set Γ) (hb : p.2 ∈ S) : missingMultiplier (p::ps) e W S = missingMultiplier ps (appendPoint e p.1) W S := by simp only [missingMultiplier, List.map_cons, List.sum_cons, Fintype.sum_option, appendPoint] simp only [hb, and_true] ac_rfl omit sectionInstance26 sectionInstance27 in lemma missingMultiplier_child_right [Fintype Γ] [DecidableEq Γ] {ι : Type*} [Fintype ι] (ps : List (Γ × Γ)) (p : Γ × Γ) (e : ι → Γ) (W : Γ → ℝ) (S : Set Γ) (ha : p.1 ∈ S) (hw : W p.1 = W p.2) : missingMultiplier (p::ps) e W S = missingMultiplier ps (appendPoint e p.2) W S := by simp only [missingMultiplier, List.map_cons, List.sum_cons, Fintype.sum_option, appendPoint] simp only [ha, true_and, hw] ac_rfl omit sectionInstance26 in lemma missingMultiplier_leaf [Fintype Γ] {ι : Type*} [Fintype ι] [DecidableEq ι] (A : Set Γ) (e : ι → Γ) (W : Γ → ℝ) (he : Function.Injective e) (heA : ∀ i, e i ∉ A) (i : ι) : missingMultiplier [] e W (insert (e i) A) = W (e i) := by simp [missingMultiplier, Set.mem_insert_iff, he.eq_iff, heA] omit sectionInstance26 sectionInstance27 in lemma insert_embedding_injective [Fintype Γ] [DecidableEq Γ] {ι : Type*} (A : Set Γ) (e : ι → Γ) (he : Function.Injective e) (heA : ∀ i, e i ∉ A) : Function.Injective (fun i => insert (e i) A) := by intro i j hij apply he have hi : e i ∈ insert (e j) A := (Set.ext_iff.mp hij (e i)).mp (Set.mem_insert _ _) exact hi.resolve_right (heA i) noncomputable def slotEdgeEnergy {ι : Type*} [Fintype ι] (ps : List (Γ × Γ)) (e : ι → Γ) (W : Γ → ℝ) (f H : Set Γ → ℝ) (ST : Set Γ × Set Γ) : ℝ := min (missingMultiplier ps e W ST.1 * f ST.1) (missingMultiplier ps e W ST.2 * f ST.2) * (H ST.1-H ST.2)^2 lemma offdiag_sum {ι : Type*} [Fintype ι] [DecidableEq ι] (E : ι → ι → ℝ) (hE : ∀ i, E i i = 0) : ∑ ij ∈ Finset.univ.filter (fun ij : ι × ι => ij.1 ≠ ij.2), E ij.1 ij.2 = ∑ i, ∑ j, E i j := by rw [Finset.sum_filter, Fintype.sum_prod_type] apply Finset.sum_congr rfl intro i _ apply Finset.sum_congr rfl intro j _ by_cases hij : i = j · subst j; simp [hE] · simp [hij] lemma transportEnergy_leaf_eq_sum {ι : Type*} [Fintype ι] [DecidableEq ι] (f H : Set Γ → ℝ) (A : Set Γ) (e : ι → Γ) (W : Γ → ℝ) (he : Function.Injective e) (heA : ∀ i, e i ∉ A) : transportEnergy [] f H A e W = (∑ ST ∈ transportEdges [] A e, slotEdgeEnergy [] e W f H ST)/2 := by have hi := insert_embedding_injective A e he heA have hp : Function.Injective (fun ij : ι × ι => (insert (e ij.1) A, insert (e ij.2) A)) := by intro ij kl h exact Prod.ext (hi (congrArg Prod.fst h)) (hi (congrArg Prod.snd h)) rw [transportEnergy_nil, transportEdges, Finset.sum_image (fun _ _ _ _ h => hp h)] simp only [slotEdgeEnergy, missingMultiplier_leaf A e W he heA] rw [offdiag_sum (fun i j => min (W (e i)*f (insert (e i) A)) (W (e j)*f (insert (e j) A)) * (H (insert (e i) A)-H (insert (e j) A))^2) (fun i => by simp)] rfl lemma transportEnergy_eq_sum (ps : List (Γ × Γ)) : ∀ {ι : Type*} [Fintype ι] [DecidableEq ι] (f H : Set Γ → ℝ) (A : Set Γ) (e : ι → Γ) (W : Γ → ℝ), Function.Injective e → (∀ i, e i ∉ A) → SlotsFresh ps (A ∪ Set.range e) → (∀ p ∈ ps, W p.1 = W p.2) → transportEnergy ps f H A e W = (∑ ST ∈ transportEdges ps A e, slotEdgeEnergy ps e W f H ST)/2 := by induction ps with | nil => intro ι _ _ f H A e W he heA _ _ exact transportEnergy_leaf_eq_sum f H A e W he heA | cons p ps ih => intro ι _ _ f H A e W he heA hps hw obtain ⟨hab,ha,hb,ht⟩ := hps have hps' : SlotsFresh (p::ps) (A ∪ Set.range e) := ⟨hab,ha,hb,ht⟩ obtain ⟨hfa,hfb⟩ := slotsFresh_child e A p ps hps' have hwt : ∀ p ∈ ps, W p.1 = W p.2 := fun q hq => hw q (List.mem_cons_of_mem _ hq) rw [transportEnergy_cons, ih f H (insert p.2 A) (appendPoint e p.1) W (appendPoint_injective e p.1 he (fun h => ha (Or.inr h))) (appendPoint_fresh e A p.1 p.2 heA hab (fun h => ha (Or.inl h)) (fun h => hb (Or.inr h))) hfa hwt, ih f H (insert p.1 A) (appendPoint e p.2) W (appendPoint_injective e p.2 he (fun h => hb (Or.inr h))) (appendPoint_fresh e A p.2 p.1 heA hab.symm (fun h => hb (Or.inl h)) (fun h => ha (Or.inr h))) hfb hwt, transportEdges, Finset.sum_union (transportEdges_disjoint ps A e p he heA hps'), ← add_div] congr 1 apply congrArg₂ (· + ·) · apply Finset.sum_congr rfl intro ST hST have hfix := transportEdges_fixed ps (insert p.2 A) (appendPoint e p.1) ST hST have hm := hfix (Set.mem_insert _ _) simp only [slotEdgeEnergy, missingMultiplier_child_left ps p e W ST.1 hm.1, missingMultiplier_child_left ps p e W ST.2 hm.2] · apply Finset.sum_congr rfl intro ST hST have hfix := transportEdges_fixed ps (insert p.1 A) (appendPoint e p.2) ST hST have hm := hfix (Set.mem_insert _ _) simp only [slotEdgeEnergy, missingMultiplier_child_right ps p e W ST.1 hm.1 (hw p (List.mem_cons_self ..)), missingMultiplier_child_right ps p e W ST.2 hm.2 (hw p (List.mem_cons_self ..))] omit sectionInstance26 sectionInstance27 in lemma transportEdges_states [Fintype Γ] [DecidableEq Γ] (ps : List (Γ × Γ)) : ∀ {ι : Type*} [Fintype ι] [DecidableEq ι] (A : Set Γ) (e : ι → Γ) (ST : Set Γ × Set Γ), ST ∈ transportEdges ps A e → ST.1 ∈ slotVertices ps A e ∧ ST.2 ∈ slotVertices ps A e := by induction ps with | nil => intro ι _ _ A e ST h rw [transportEdges] at h obtain ⟨ij,_,rfl⟩ := Finset.mem_image.mp h rw [slotVertices] exact ⟨Finset.mem_image.mpr ⟨ij.1,Finset.mem_univ _,rfl⟩, Finset.mem_image.mpr ⟨ij.2,Finset.mem_univ _,rfl⟩⟩ | cons p ps ih => intro ι _ _ A e ST h rw [transportEdges] at h rw [slotVertices] rcases Finset.mem_union.mp h with h | h · have hh := ih _ _ _ h exact ⟨Finset.mem_union_left _ hh.1,Finset.mem_union_left _ hh.2⟩ · have hh := ih _ _ _ h exact ⟨Finset.mem_union_right _ hh.1,Finset.mem_union_right _ hh.2⟩ lemma transportEdges_adjacent (ps : List (Γ × Γ)) : ∀ {ι : Type*} [Fintype ι] [DecidableEq ι] (A : Set Γ) (e : ι → Γ), Function.Injective e → (∀ i, e i ∉ A) → SlotsFresh ps (A ∪ Set.range e) → ∀ ST ∈ transportEdges ps A e, ExchangeAdjacent ST.1 ST.2 := by induction ps with | nil => intro ι _ _ A e he heA _ ST h rw [transportEdges] at h obtain ⟨ij,hij,rfl⟩ := Finset.mem_image.mp h exact ⟨A,e ij.1,e ij.2,fun h => (Finset.mem_filter.mp hij).2 (he h), heA _,heA _,rfl,rfl⟩ | cons p ps ih => intro ι _ _ A e he heA hps ST h obtain ⟨hab,ha,hb,ht⟩ := hps have hps' : SlotsFresh (p::ps) (A ∪ Set.range e) := ⟨hab,ha,hb,ht⟩ obtain ⟨hfa,hfb⟩ := slotsFresh_child e A p ps hps' rw [transportEdges] at h rcases Finset.mem_union.mp h with h | h · exact ih (insert p.2 A) (appendPoint e p.1) (appendPoint_injective e p.1 he (fun h => ha (Or.inr h))) (appendPoint_fresh e A p.1 p.2 heA hab (fun h => ha (Or.inl h)) (fun h => hb (Or.inr h))) hfa ST h · exact ih (insert p.1 A) (appendPoint e p.2) (appendPoint_injective e p.2 he (fun h => hb (Or.inr h))) (appendPoint_fresh e A p.2 p.1 heA hab.symm (fun h => hb (Or.inl h)) (fun h => ha (Or.inr h))) hfb ST h noncomputable def slotGraphEdges {ι : Type*} [Fintype ι] (ps : List (Γ × Γ)) (A : Set Γ) (e : ι → Γ) : Finset (Set Γ × Set Γ) := ((slotVertices ps A e).product (slotVertices ps A e)).filter (fun ST => ExchangeAdjacent ST.1 ST.2) noncomputable def slotGraphEnergy {ι : Type*} [Fintype ι] (ps : List (Γ × Γ)) (f H : Set Γ → ℝ) (A : Set Γ) (e : ι → Γ) (W : Γ → ℝ) : ℝ := (∑ ST ∈ slotGraphEdges ps A e, slotEdgeEnergy ps e W f H ST)/2 omit sectionInstance26 sectionInstance27 in lemma missingMultiplier_nonneg [Fintype Γ] [DecidableEq Γ] {ι : Type*} [Fintype ι] (ps : List (Γ × Γ)) (e : ι → Γ) (W : Γ → ℝ) (hW : ∀ i, 0 ≤ W i) (S : Set Γ) : 0 ≤ missingMultiplier ps e W S := by apply add_nonneg · exact Finset.sum_nonneg (fun i _ => by split_ifs <;> simp_all) · apply List.sum_nonneg intro x hx obtain ⟨p,_,rfl⟩ := List.mem_map.mp hx split_ifs <;> simp_all lemma transportEnergy_le_graphEnergy {ι : Type*} [Fintype ι] [DecidableEq ι] (ps : List (Γ × Γ)) (f H : Set Γ → ℝ) (A : Set Γ) (e : ι → Γ) (W : Γ → ℝ) (he : Function.Injective e) (heA : ∀ i, e i ∉ A) (hps : SlotsFresh ps (A ∪ Set.range e)) (hw : ∀ p ∈ ps, W p.1 = W p.2) (hf : ∀ S, 0 ≤ f S) (hW : ∀ i, 0 ≤ W i) : transportEnergy ps f H A e W ≤ slotGraphEnergy ps f H A e W := by rw [transportEnergy_eq_sum ps f H A e W he heA hps hw] apply div_le_div_of_nonneg_right _ (by norm_num) apply Finset.sum_le_sum_of_subset_of_nonneg · intro ST hST apply Finset.mem_filter.mpr exact ⟨Finset.mem_product.mpr (transportEdges_states ps A e ST hST), transportEdges_adjacent ps A e he heA hps ST hST⟩ · intro ST _ _ apply mul_nonneg _ (sq_nonneg _) exact le_min (mul_nonneg (missingMultiplier_nonneg ps e W hW ST.1) (hf _)) (mul_nonneg (missingMultiplier_nonneg ps e W hW ST.2) (hf _)) theorem transport_graph_bound (ps : List (Γ × Γ)) (f H : Set Γ → ℝ) (A : Set Γ) (p d : Γ) (W : Γ → ℝ) (hf : ∀ S, 0 < f S) (hSig : HasSlotSignature f) (hpd : p ≠ d) (hpA : p ∉ A) (hdA : d ∉ A) (hps : SlotsFresh ps (A ∪ Set.range (rootEmbedding p d))) (hW : ∀ i, 0 < W i) (hw : ∀ p ∈ ps, W p.1 = W p.2) : (slotTotal ps (fun S => f S*H S) (insert p A) / slotTotal ps f (insert p A) - slotTotal ps (fun S => f S*H S) (insert d A) / slotTotal ps f (insert d A))^2 ≤ rootCoefficient ps f A p d W * slotGraphEnergy ps f H A (rootEmbedding p d) W := by apply (transport_root_bound ps f H A p d W hf hSig hpd hpA hdA hps hW hw).trans apply mul_le_mul_of_nonneg_left _ (rootCoefficient_pos ps f hf A p d W hps hW).le apply transportEnergy_le_graphEnergy ps f H A (rootEmbedding p d) W (rootEmbedding_injective p d hpd) _ hps hw (fun S => (hf S).le) (fun i => (hW i).le) intro i cases i <;> assumption end TransportGraph section CoefficientInequalities open scoped BigOperators Classical Matrix variable {ι : Type*} [sectionInstance28 : Fintype ι] [sectionInstance29 : DecidableEq ι] omit sectionInstance29 in lemma coeffDeriv_eq_sum_outside [DecidableEq ι] (a : ι → ℝ) (f : Set ι → ℝ) (A : Set ι) : coeffDeriv a f A = ∑ i : {i // i ∉ A}, a i.val * f (insert i.val A) := by classical unfold coeffDeriv let g : ι → ℝ := fun i => if i ∈ A then 0 else a i * f (insert i A) change (∑ i, g i) = _ rw [← Fintype.sum_subtype_add_sum_subtype (fun i => i ∉ A) g] have hz : (∑ i : {i // ¬i ∉ A}, g i.val) = 0 := by apply Finset.sum_eq_zero intro i _ simp only [g, ite_eq_left (not_not.mp i.property)] rw [hz,add_zero] apply Finset.sum_congr rfl intro i _ simp only [g, ite_eq_right i.property] lemma faceHessian_bilin_derivatives (f : Set ι → ℝ) (a b : ι → ℝ) (A : Set ι) : (faceHessian f A).toBilin' (fun i => a i.val) (fun i => b i.val) = coeffDeriv a (coeffDeriv b f) A := by classical rw [coeffDeriv_eq_sum_outside] simp only [Matrix.toBilin'_apply, faceHessian] apply Finset.sum_congr rfl intro i _ unfold coeffDeriv let g : ι → ℝ := fun j => @ite ℝ (j ∈ insert i.val A) (Classical.propDecidable _) 0 (b j * f (insert j (insert i.val A))) change _ = a i.val * ∑ j, g j have heq : (∑ j, g j) = ∑ j : {j // j ∉ A}, g j.val := by rw [← Fintype.sum_subtype_add_sum_subtype (fun j => j ∉ A) g] have hz : (∑ j : {j // ¬j ∉ A}, g j.val) = 0 := by apply Finset.sum_eq_zero intro j _ simp only [g, ite_eq_left (Set.mem_insert_of_mem _ (not_not.mp j.property))] rw [hz,add_zero] rw [heq, Finset.mul_sum] apply Finset.sum_congr rfl intro j _ dsimp only [g] by_cases hij : i = j · subst j; simp [] · have hji : j.val ∉ insert i.val A := by simp only [Set.mem_insert_iff, not_or] exact ⟨fun h => hij (Subtype.ext h.symm),j.property⟩ rw [ite_eq_right hji] simp only [hij, ite_false] have hset : A ∪ {i.val,j.val} = insert j.val (insert i.val A) := by ext x; simp; tauto rw [hset] ring lemma onePositive_pair_bound {V : Type*} [AddCommGroup V] [Module ℝ V] (B : LinearMap.BilinForm ℝ V) (hB : OnePositive B) (hS : B.IsSymm) (u v : V) (hu : 0 < B u u) : B u u * B v v ≤ (B u v)^2 := by have h := (le_div_iff₀ hu).mp (onePositive_quadratic_bound B hB hS u v hu) rw [hS.eq v u] at h nlinarith lemma onePositive_triple_bound {V : Type*} [AddCommGroup V] [Module ℝ V] (B : LinearMap.BilinForm ℝ V) (hB : OnePositive B) (hS : B.IsSymm) (u e v : V) (he : 0 < B e e) (hue : 0 < B u e) (hve : 0 < B v e) (hu : 0 ≤ B u u) (hv : 0 ≤ B v v) : B u v * B e e ≤ 2 * B u e * B v e := by have h := (le_div_iff₀ he).mp (onePositive_quadratic_bound B hB hS e ((B v e) • u + (B u e) • v) he) have hvu : B v u = B u v := hS.eq v u simp only [map_add, map_smul, LinearMap.add_apply, LinearMap.smul_apply, smul_eq_mul, hvu] at h have hn₁ := mul_nonneg (mul_nonneg (sq_nonneg (B v e)) hu) he.le have hn₂ := mul_nonneg (mul_nonneg (sq_nonneg (B u e)) hv) he.le have hh : (2 * B u e * B v e) * (B u v * B e e) ≤ (2 * B u e * B v e) * (2 * B u e * B v e) := by nlinarith [h,hn₁,hn₂] exact (mul_le_mul_iff_right₀ (mul_pos (mul_pos (by norm_num) hue) hve)).mp hh lemma coeffDeriv_comm (a b : ι → ℝ) (f : Set ι → ℝ) (A : Set ι) : coeffDeriv a (coeffDeriv b f) A = coeffDeriv b (coeffDeriv a f) A := by rw [← faceHessian_bilin_derivatives, ← faceHessian_bilin_derivatives] exact (matrix_bilin_symm _ (faceHessian_symm f A)).eq _ _ lemma coeffDeriv_pair_twice (p : ι × ι) (f : Set ι → ℝ) (A : Set ι) (hp : p.1 ≠ p.2) (ha : p.1 ∉ A) (hb : p.2 ∉ A) : coeffDeriv (pairDirection p) (coeffDeriv (pairDirection p) f) A = 2 * f (insert p.1 (insert p.2 A)) := by unfold pairDirection rw [coeffDeriv_pair p.1 p.2 hp _ A ha hb] simp only [coeffDeriv_slot] simp [hp, hp.symm, ha, hb, Set.insert_comm, two_mul] lemma faceHessian_nonnegative_vectors (f : Set ι → ℝ) (hf : ∀ S, 0 ≤ f S) (A : Set ι) (a b : ι → ℝ) (ha : ∀ i, 0 ≤ a i) (hb : ∀ i, 0 ≤ b i) : 0 ≤ (faceHessian f A).toBilin' (fun i => a i.val) (fun i => b i.val) := by simp only [Matrix.toBilin'_apply] apply Finset.sum_nonneg intro i _ apply Finset.sum_nonneg intro j _ apply mul_nonneg _ (hb _) apply mul_nonneg (ha _) unfold faceHessian split_ifs · exact le_rfl · exact hf _ theorem coefficient_pair (ps : List (ι × ι)) (f : Set ι → ℝ) (hf : ∀ S, 0 < f S) (hsig : HasSlotSignature f) (A : Set ι) (p r : ι × ι) (hpr : SlotsFresh (p::r::ps) A) : 4 * slotTotal ps f (insert p.1 (insert p.2 A)) * slotTotal ps f (insert r.1 (insert r.2 A)) ≤ (slotTotal (p::r::ps) f A)^2 := by obtain ⟨hp,hpa,hpb,hr,hra,hrb,hps⟩ := hpr have hra' : r.1 ∉ A := fun h => hra (Or.inr (Or.inr h)) have hrb' : r.2 ∉ A := fun h => hrb (Or.inr (Or.inr h)) let B := (faceHessian (slotTotal ps f) A).toBilin' let u : {i // i ∉ A} → ℝ := fun i => pairDirection p i.val let v : {i // i ∉ A} → ℝ := fun i => pairDirection r i.val have huu : B u u = 2 * slotTotal ps f (insert p.1 (insert p.2 A)) := by rw [faceHessian_bilin_derivatives] exact coeffDeriv_pair_twice p _ A hp hpa hpb have hvv : B v v = 2 * slotTotal ps f (insert r.1 (insert r.2 A)) := by rw [faceHessian_bilin_derivatives] exact coeffDeriv_pair_twice r _ A hr hra' hrb' have huv : B u v = slotTotal (p::r::ps) f A := by exact faceHessian_bilin_derivatives _ _ _ _ have hpos : 0 < B u u := by rw [huu] apply mul_pos (by norm_num) apply slotTotal_pos ps f hf _ (hps.mono _) intro x hx simp only [Set.mem_insert_iff] at hx ⊢ tauto have h := onePositive_pair_bound B (hsig ps A) (matrix_bilin_symm _ (faceHessian_symm _ _)) u v hpos rw [huu,hvv,huv] at h nlinarith lemma SlotsFresh.tail {ps : List (ι × ι)} {p : ι × ι} {A : Set ι} (h : SlotsFresh (p::ps) A) : SlotsFresh ps A := h.2.2.2.mono (by intro x hx; exact Or.inr (Or.inr hx)) omit sectionInstance28 sectionInstance29 in lemma SlotsFresh.swap [Fintype ι] [DecidableEq ι] {ps : List (ι × ι)} {p r : ι × ι} {A : Set ι} (h : SlotsFresh (p::r::ps) A) : SlotsFresh (r::p::ps) A := by obtain ⟨hp,hpa,hpb,hr,hra,hrb,hps⟩ := h refine ⟨hr,?_,?_,hp,?_,?_,?_⟩ · exact fun hx => hra (Or.inr (Or.inr hx)) · exact fun hx => hrb (Or.inr (Or.inr hx)) · simp only [Set.mem_insert_iff, not_or] at hra hrb ⊢ exact ⟨Ne.symm hra.1,Ne.symm hrb.1,hpa⟩ · simp only [Set.mem_insert_iff, not_or] at hra hrb ⊢ exact ⟨Ne.symm hra.2.1,Ne.symm hrb.2.1,hpb⟩ · convert hps using 1 ; ext x ; simp ; tauto lemma coeffDeriv_pair_repeated (p r : ι × ι) (f : Set ι → ℝ) (A : Set ι) (hp : p.1 ≠ p.2) (ha : p.1 ∉ A) (hb : p.2 ∉ A) : coeffDeriv (pairDirection r) (coeffDeriv (pairDirection p) (coeffDeriv (pairDirection p) f)) A = 2 * coeffDeriv (pairDirection r) f (insert p.1 (insert p.2 A)) := by rw [coeffDeriv_comm (pairDirection r) (pairDirection p)] have h : coeffDeriv (pairDirection r) (coeffDeriv (pairDirection p) f) = coeffDeriv (pairDirection p) (coeffDeriv (pairDirection r) f) := by funext S exact coeffDeriv_comm _ _ _ _ rw [h, coeffDeriv_pair_twice p _ A hp ha hb] theorem coefficient_triple (ps : List (ι × ι)) (f : Set ι → ℝ) (hf : ∀ S, 0 < f S) (hsig : HasSlotSignature f) (A : Set ι) (p r t : ι × ι) (hprt : SlotsFresh (p::r::t::ps) A) : slotTotal (t::ps) f (insert r.1 (insert r.2 A)) * slotTotal (p::ps) f (insert t.1 (insert t.2 A)) ≤ slotTotal (p::r::t::ps) f A * slotTotal (r::ps) f (insert t.1 (insert t.2 A)) := by have hrt := hprt.tail have ht := hrt.tail have hr := hrt.1 have hra := hrt.2.1 have hrb := hrt.2.2.1 have htr : SlotsFresh (r::ps) (insert t.1 (insert t.2 A)) := hrt.swap.2.2.2 let g := slotTotal ps f let B := (faceHessian (coeffDeriv (pairDirection t) g) A).toBilin' let u : {i // i ∉ A} → ℝ := fun i => pairDirection p i.val let e : {i // i ∉ A} → ℝ := fun i => pairDirection r i.val let v : {i // i ∉ A} → ℝ := fun i => pairDirection t i.val have hee : B e e = 2 * slotTotal (t::ps) f (insert r.1 (insert r.2 A)) := by rw [faceHessian_bilin_derivatives] exact coeffDeriv_pair_twice r _ A hr hra hrb have hue : B u e = slotTotal (p::r::t::ps) f A := faceHessian_bilin_derivatives _ _ _ _ have hve : B v e = 2 * slotTotal (r::ps) f (insert t.1 (insert t.2 A)) := by rw [faceHessian_bilin_derivatives, coeffDeriv_comm (pairDirection t) (pairDirection r)] exact coeffDeriv_pair_repeated t r _ A ht.1 ht.2.1 ht.2.2.1 have huv : B u v = 2 * slotTotal (p::ps) f (insert t.1 (insert t.2 A)) := by rw [faceHessian_bilin_derivatives] exact coeffDeriv_pair_repeated t p _ A ht.1 ht.2.1 ht.2.2.1 have hepos : 0 < B e e := by rw [hee] exact mul_pos (by norm_num) (slotTotal_pos _ f hf _ hrt.2.2.2) have huepos : 0 < B u e := by rw [hue] exact slotTotal_pos _ f hf _ hprt have hvepos : 0 < B v e := by rw [hve] exact mul_pos (by norm_num) (slotTotal_pos _ f hf _ htr) have hn : ∀ S, 0 ≤ coeffDeriv (pairDirection t) g S := slotTotal_nonneg (t::ps) f (fun S => (hf S).le) have h := onePositive_triple_bound B (hsig (t::ps) A) (matrix_bilin_symm _ (faceHessian_symm _ _)) u e v hepos huepos hvepos (faceHessian_nonnegative_vectors _ hn A _ _ (slotDirection_nonneg _) (slotDirection_nonneg _)) (faceHessian_nonnegative_vectors _ hn A _ _ (slotDirection_nonneg _) (slotDirection_nonneg _)) rw [huv,hee,hue,hve] at h nlinarith theorem scores_have_sink [Nonempty ι] (a : ι → ι → ℝ) (hpair : ∀ i j, i ≠ j → a i j * a j i ≤ 1/16) (htriple : ∀ i j k, i ≠ j → j ≠ k → i ≠ k → a i j * a j k ≤ a i k) : ∃ k, ∀ t, k ≠ t → a k t ≤ 1 := by classical let out : ι → Finset ι := fun i => Finset.univ.filter (fun j => i ≠ j ∧ 1 < a i j) obtain ⟨k,_,hk⟩ := Finset.exists_min_image Finset.univ (fun i => (out i).card) Finset.univ_nonempty refine ⟨k,?_⟩ intro t hkt by_contra hkt' have hat : 1 < a k t := lt_of_not_ge hkt' have hnocycle : ∀ i j, i ≠ j → 1 < a i j → ¬ 1 < a j i := by intro i j hij ha hb have hm : 1 < a i j * a j i := by nlinarith [mul_pos (sub_pos.mpr ha) (sub_pos.mpr hb)] have hp := hpair i j hij linarith have hsub : out t ⊆ out k := by intro j hj obtain ⟨htj,haj⟩ := (Finset.mem_filter.mp hj).2 have hkj : k ≠ j := by intro heq subst j exact hnocycle k t hkt hat haj apply Finset.mem_filter.mpr refine ⟨Finset.mem_univ _,hkj,?_⟩ have hm : 1 < a k t * a t j := by nlinarith [mul_pos (sub_pos.mpr hat) (sub_pos.mpr haj)] exact hm.trans_le (htriple k t j hkt htj hkj) have ht : t ∈ out k := Finset.mem_filter.mpr ⟨Finset.mem_univ _,hkt,hat⟩ have htt : t ∉ out t := by simp [out] have hss : out t ⊂ out k := Finset.ssubset_iff_subset_ne.mpr ⟨hsub,fun heq => htt (heq ▸ ht)⟩ exact (not_lt_of_ge (hk t (Finset.mem_univ _))) (Finset.card_lt_card hss) end CoefficientInequalities section MatroidWeights open scoped BigOperators Classical Matrix variable {ι : Type*} [sectionInstance30 : Fintype ι] [sectionInstance31 : DecidableEq ι] omit sectionInstance31 in lemma coeffDeriv_scale [DecidableEq ι] (a : ι → ℝ) (f : Set ι → ℝ) (c : ℝ) (A : Set ι) : coeffDeriv a (fun S => c * f S) A = c * coeffDeriv a f A := by simp only [coeffDeriv, Finset.mul_sum] apply Finset.sum_congr rfl intro i _ split_ifs <;> ring lemma coeffDerivs_scale (as : List (ι → ℝ)) (f : Set ι → ℝ) (c : ℝ) (A : Set ι) : coeffDerivs as (fun S => c * f S) A = c * coeffDerivs as f A := by induction as generalizing A with | nil => rfl | cons a as ih => change coeffDeriv a (coeffDerivs as (fun S => c * f S)) A = _ have h : coeffDerivs as (fun S => c * f S) = fun S => c * coeffDerivs as f S := by funext S; exact ih S rw [h,coeffDeriv_scale] rfl lemma HasSlotSignature.scale {f : Set ι → ℝ} (hf : HasSlotSignature f) (c : ℝ) (hc : 0 < c) : HasSlotSignature (fun S => c * f S) := by intro ps A have heq : faceHessian (slotTotal ps (fun S => c * f S)) A = c • faceHessian (slotTotal ps f) A := by ext i j simp only [faceHessian, Matrix.smul_apply, smul_eq_mul] split_ifs · simp · exact coeffDerivs_scale _ _ _ _ rw [heq,map_smul] exact onePositive_smul _ (hf ps A) c hc noncomputable def matroidWeight (M : Matroid ι) (n : ℕ) (q : ℝ) (S : Set ι) : ℝ := q ^ (n - (M.eRk S).toNat) omit sectionInstance30 sectionInstance31 in lemma matroidWeight_eq_scaled [Fintype ι] [DecidableEq ι] (M : Matroid ι) (n : ℕ) (hR : M.eRank = (n : ℕ∞)) (q : ℝ) (hq : 0 < q) (S : Set ι) : matroidWeight M n q S = q^n * rankWeight M q S := by have hr : (M.eRk S).toNat ≤ n := by have h := M.eRk_le_eRank S rw [hR] at h exact ENat.toNat_le_of_le_natCast h unfold matroidWeight rankWeight rw [inv_pow, ← div_eq_mul_inv] exact (eq_div_iff (ne_of_gt (pow_pos hq _))).mpr (by rw [← pow_add, Nat.sub_add_cancel hr]) omit sectionInstance30 sectionInstance31 in lemma matroidWeight_pos [Fintype ι] [DecidableEq ι] (M : Matroid ι) (n : ℕ) (q : ℝ) (hq : 0 < q) (S : Set ι) : 0 < matroidWeight M n q S := pow_pos hq _ lemma matroidWeight_signature (M : Matroid ι) (hE : M.E = Set.univ) (n : ℕ) (hR : M.eRank = (n : ℕ∞)) (q : ℝ) (hq : 0 < q) (hq1 : q ≤ 1) : HasSlotSignature (matroidWeight M n q) := by have heq : matroidWeight M n q = fun S => q^n * rankWeight M q S := by funext S; exact matroidWeight_eq_scaled M n hR q hq S rw [heq] exact (rankWeight_hasSlotSignature M hE q hq hq1).scale _ (pow_pos hq _) omit sectionInstance31 in lemma dual_rank_equal_complement [DecidableEq ι] (M : Matroid ι) (hE : M.E = Set.univ) (n : ℕ) (hR : M.eRank = (n : ℕ∞)) (S : Set ι) (hS : S.ncard = n) : M✶.eRk S = M.eRk Sᶜ := by have he := M.eRk_dual_add_eRank S (by simp [hE]) have hencard : S.encard = (n : ℕ∞) := by rw [← Set.coe_ncard_eq_encard S, hS] rw [hE, ← Set.compl_eq_univ_sdiff, hR, hencard] at he exact ENat.add_left_injective_of_ne_top (by simp) he omit sectionInstance31 in lemma dual_eRank_half [DecidableEq ι] (M : Matroid ι) (hE : M.E = Set.univ) (n : ℕ) (hR : M.eRank = (n : ℕ∞)) (hcard : Fintype.card ι = 2*n) : M✶.eRank = (n : ℕ∞) := by have h := M.eRank_add_eRank_dual rw [hE, Set.encard_univ, hR, ENat.card_eq_coe_fintype_card, hcard] at h have h' : (n : ℕ∞) + M✶.eRank = (n : ℕ∞) + n := by simpa [Nat.cast_mul, two_mul] using h exact ENat.add_right_injective_of_ne_top (by simp) h' lemma matroidWeight_dual_complement (M : Matroid ι) (hE : M.E = Set.univ) (n : ℕ) (hR : M.eRank = (n : ℕ∞)) (q : ℝ) (S : Set ι) (hS : S.ncard = n) : matroidWeight M✶ n q S = matroidWeight M n q Sᶜ := by unfold matroidWeight rw [dual_rank_equal_complement M hE n hR S hS] theorem paired_matroid_weight_signatures (M : Matroid ι) (hE : M.E = Set.univ) (n : ℕ) (hR : M.eRank = (n : ℕ∞)) (hcard : Fintype.card ι = 2*n) (q : ℝ) (hq : 0 < q) (hq1 : q ≤ 1) : HasSlotSignature (matroidWeight M n q) ∧ HasSlotSignature (matroidWeight M✶ n q) := by exact ⟨matroidWeight_signature M hE n hR q hq hq1, matroidWeight_signature M✶ (by simpa) n (dual_eRank_half M hE n hR hcard) q hq hq1⟩ end MatroidWeights section IndexedSlotCoefficients open scoped BigOperators Classical variable {ι : Type*} [sectionInstance32 : Fintype ι] [DecidableEq ι] lemma SlotsFresh.perm {ps qs : List (ι × ι)} (hperm : ps.Perm qs) (A : Set ι) : SlotsFresh ps A ↔ SlotsFresh qs A := by induction hperm generalizing A with | nil => rfl | cons p h ih => change (_ ∧ _ ∧ _ ∧ SlotsFresh _ _) ↔ (_ ∧ _ ∧ _ ∧ SlotsFresh _ _) rw [ih] | swap p r ps => exact ⟨SlotsFresh.swap,SlotsFresh.swap⟩ | trans h₁ h₂ ih₁ ih₂ => exact (ih₁ A).trans (ih₂ A) lemma slotTotal_perm {ps qs : List (ι × ι)} (hperm : ps.Perm qs) (f : Set ι → ℝ) : slotTotal ps f = slotTotal qs f := by induction hperm with | nil => rfl | cons p h ih => change coeffDeriv _ (slotTotal _ f) = coeffDeriv _ (slotTotal _ f) rw [ih] | swap p r ps => funext A exact coeffDeriv_comm _ _ _ _ | trans h₁ h₂ ih₁ ih₂ => exact ih₁.trans ih₂ noncomputable def slotDefect (ps : List (ι × ι)) (f : Set ι → ℝ) (A : Set ι) (p r : ι × ι) : ℝ := slotTotal ((ps.erase p).erase r) f (insert r.1 (insert r.2 A)) omit sectionInstance32 in lemma slots_perm_two [Fintype ι] {ps : List (ι × ι)} {p r : ι × ι} (hp : p ∈ ps) (hr : r ∈ ps) (hpr : p ≠ r) : ps.Perm (p::r::(ps.erase p).erase r) := by exact (List.perm_cons_erase hp).trans ((List.perm_cons_erase ((List.mem_erase_of_ne hpr.symm).mpr hr)).cons p) lemma slotDefect_perm {ps qs : List (ι × ι)} (hperm : ps.Perm qs) (f : Set ι → ℝ) (A : Set ι) (p r : ι × ι) : slotDefect ps f A p r = slotDefect qs f A p r := by unfold slotDefect rw [slotTotal_perm ((hperm.erase p).erase r)] lemma slotDefect_pos (ps : List (ι × ι)) (f : Set ι → ℝ) (hf : ∀ S, 0 < f S) (A : Set ι) (hps : SlotsFresh ps A) (p r : ι × ι) (hp : p ∈ ps) (hr : r ∈ ps) (hpr : p ≠ r) : 0 < slotDefect ps f A p r := by have hh := (SlotsFresh.perm (slots_perm_two hp hr hpr) A).mp hps apply slotTotal_pos _ f hf _ (hh.2.2.2.2.2.2.mono _) intro x hx simp only [Set.mem_insert_iff] at hx ⊢ tauto lemma slotDefect_pair_bound (ps : List (ι × ι)) (f : Set ι → ℝ) (hf : ∀ S, 0 < f S) (hsig : HasSlotSignature f) (A : Set ι) (hps : SlotsFresh ps A) (p r : ι × ι) (hp : p ∈ ps) (hr : r ∈ ps) (hpr : p ≠ r) : 4 * slotDefect ps f A p r * slotDefect ps f A r p ≤ (slotTotal ps f A)^2 := by have hperm := slots_perm_two hp hr hpr have h := coefficient_pair ((ps.erase p).erase r) f hf hsig A p r ((SlotsFresh.perm hperm A).mp hps) rw [← slotTotal_perm hperm f] at h unfold slotDefect rw [List.erase_comm r p] nlinarith lemma slots_perm_three {ps : List (ι × ι)} {p r t : ι × ι} (hp : p ∈ ps) (hr : r ∈ ps) (ht : t ∈ ps) (hpr : p ≠ r) (hrt : r ≠ t) (hpt : p ≠ t) : ps.Perm (p::r::t::((ps.erase p).erase r).erase t) := by have ht' : t ∈ (ps.erase p).erase r := (List.mem_erase_of_ne hrt.symm).mpr ((List.mem_erase_of_ne hpt.symm).mpr ht) exact (slots_perm_two hp hr hpr).trans ((List.perm_cons_erase ht').cons r |>.cons p) lemma slotDefect_triple_bound (ps : List (ι × ι)) (f : Set ι → ℝ) (hf : ∀ S, 0 < f S) (hsig : HasSlotSignature f) (A : Set ι) (hps : SlotsFresh ps A) (p r t : ι × ι) (hp : p ∈ ps) (hr : r ∈ ps) (ht : t ∈ ps) (hpr : p ≠ r) (hrt : r ≠ t) (hpt : p ≠ t) : slotDefect ps f A p r * slotDefect ps f A r t ≤ slotTotal ps f A * slotDefect ps f A p t := by have hperm := slots_perm_three hp hr ht hpr hrt hpt have h := coefficient_triple (((ps.erase p).erase r).erase t) f hf hsig A p r t ((SlotsFresh.perm hperm A).mp hps) rw [slotDefect_perm hperm, slotDefect_perm hperm, slotDefect_perm hperm, slotTotal_perm hperm] simpa [slotDefect, hpr, hpr.symm, hrt, hrt.symm, hpt, hpt.symm] using h lemma coefficient_scores_sink {J : Type*} [Fintype J] [DecidableEq J] [Nonempty J] (c d : J → J → ℝ) (z v : ℝ) (hz : 0 < z) (hv : 0 < v) (hc : ∀ i j, i ≠ j → 0 ≤ c i j) (hd : ∀ i j, i ≠ j → 0 ≤ d i j) (hcp : ∀ i j, i ≠ j → 4*c i j*c j i ≤ z^2) (hdp : ∀ i j, i ≠ j → 4*d i j*d j i ≤ v^2) (hct : ∀ i j k, i ≠ j → j ≠ k → i ≠ k → c i j*c j k ≤ z*c i k) (hdt : ∀ i j k, i ≠ j → j ≠ k → i ≠ k → d i j*d j k ≤ v*d i k) : ∃ i, ∀ j, i ≠ j → c i j*d j i ≤ z*v := by let a : J → J → ℝ := fun i j => (c i j * d j i)/(z*v) have hzv : 0 < z*v := mul_pos hz hv have hp : ∀ i j, i ≠ j → a i j*a j i ≤ 1/16 := by intro i j hij dsimp [a] rw [div_mul_div_comm] apply (div_le_iff₀ (mul_pos hzv hzv)).mpr have h := mul_le_mul (hcp i j hij) (hdp j i hij.symm) (mul_nonneg (mul_nonneg (by norm_num) (hd j i hij.symm)) (hd i j hij)) (sq_nonneg z) nlinarith have ht : ∀ i j k, i ≠ j → j ≠ k → i ≠ k → a i j*a j k ≤ a i k := by intro i j k hij hjk hik dsimp [a] rw [div_mul_div_comm] apply (div_le_iff₀ (mul_pos hzv hzv)).mpr have h := mul_le_mul (hct i j k hij hjk hik) (hdt k j i hjk.symm hij.symm hik.symm) (mul_nonneg (hd k j hjk.symm) (hd j i hij.symm)) (mul_nonneg hz.le (hc i k hik)) have heq : c i k*d k i/(z*v)*(z*v*(z*v)) = z*c i k*(v*d k i) := by field_simp rw [heq] nlinarith obtain ⟨i,hi⟩ := scores_have_sink a hp ht refine ⟨i,fun j hij => ?_⟩ exact (div_le_iff₀ hzv).mp (hi j hij) |>.trans_eq (one_mul _) theorem slot_scores_have_sink_forward (ps gs : List (ι × ι)) (f : Set ι → ℝ) (hf : ∀ S, 0 < f S) (hsig : HasSlotSignature f) (A B : Set ι) (hps : SlotsFresh ps A) (hgs : SlotsFresh gs B) (hsub : ∀ p ∈ ps, p ∈ gs) (hne : ps ≠ []) : ∃ p ∈ ps, ∀ r ∈ ps, p ≠ r → slotDefect ps f A p r * slotDefect gs f B r p ≤ slotTotal ps f A * slotTotal gs f B := by classical let J := {p : ι × ι // p ∈ ps} have : Nonempty J := by obtain ⟨p,hp⟩ := List.exists_mem_of_ne_nil ps hne exact ⟨⟨p,hp⟩⟩ have hne' : ∀ p r : J, p ≠ r → p.val ≠ r.val := fun p r h he => h (Subtype.ext he) obtain ⟨p,hp⟩ := coefficient_scores_sink (fun p r : J => slotDefect ps f A p.val r.val) (fun p r : J => slotDefect gs f B p.val r.val) (slotTotal ps f A) (slotTotal gs f B) (slotTotal_pos ps f hf A hps) (slotTotal_pos gs f hf B hgs) (fun p r h => (slotDefect_pos ps f hf A hps p r p.property r.property (hne' p r h)).le) (fun p r h => (slotDefect_pos gs f hf B hgs p r (hsub p p.property) (hsub r r.property) (hne' p r h)).le) (fun p r h => slotDefect_pair_bound ps f hf hsig A hps p r p.property r.property (hne' p r h)) (fun p r h => slotDefect_pair_bound gs f hf hsig B hgs p r (hsub p p.property) (hsub r r.property) (hne' p r h)) (fun p r t h₁ h₂ h₃ => slotDefect_triple_bound ps f hf hsig A hps p r t p.property r.property t.property (hne' p r h₁) (hne' r t h₂) (hne' p t h₃)) (fun p r t h₁ h₂ h₃ => slotDefect_triple_bound gs f hf hsig B hgs p r t (hsub p p.property) (hsub r r.property) (hsub t t.property) (hne' p r h₁) (hne' r t h₂) (hne' p t h₃)) refine ⟨p.val,p.property,?_⟩ intro r hr hpr exact hp ⟨r,hr⟩ (fun h => hpr (congrArg Subtype.val h)) theorem slot_scores_have_sink (ps gs : List (ι × ι)) (f : Set ι → ℝ) (hf : ∀ S, 0 < f S) (hsig : HasSlotSignature f) (A B : Set ι) (hps : SlotsFresh ps A) (hgs : SlotsFresh gs B) (hsub : ∀ p ∈ ps, p ∈ gs) (hne : ps ≠ []) : ∃ p ∈ ps, ∀ r ∈ ps, p ≠ r → slotDefect ps f A r p * slotDefect gs f B p r ≤ slotTotal ps f A * slotTotal gs f B := by classical let J := {p : ι × ι // p ∈ ps} have : Nonempty J := by obtain ⟨p,hp⟩ := List.exists_mem_of_ne_nil ps hne exact ⟨⟨p,hp⟩⟩ have hne' : ∀ p r : J, p ≠ r → p.val ≠ r.val := fun p r h he => h (Subtype.ext he) obtain ⟨p,hp⟩ := coefficient_scores_sink (fun p r : J => slotDefect ps f A r.val p.val) (fun p r : J => slotDefect gs f B r.val p.val) (slotTotal ps f A) (slotTotal gs f B) (slotTotal_pos ps f hf A hps) (slotTotal_pos gs f hf B hgs) (fun p r h => (slotDefect_pos ps f hf A hps r p r.property p.property (hne' r p h.symm)).le) (fun p r h => (slotDefect_pos gs f hf B hgs r p (hsub r r.property) (hsub p p.property) (hne' r p h.symm)).le) (fun p r h => slotDefect_pair_bound ps f hf hsig A hps r p r.property p.property (hne' r p h.symm)) (fun p r h => slotDefect_pair_bound gs f hf hsig B hgs r p (hsub r r.property) (hsub p p.property) (hne' r p h.symm)) (fun p r t h₁ h₂ h₃ => by simpa only [mul_comm] using slotDefect_triple_bound ps f hf hsig A hps t r p t.property r.property p.property (hne' t r h₂.symm) (hne' r p h₁.symm) (hne' t p h₃.symm)) (fun p r t h₁ h₂ h₃ => by simpa only [mul_comm] using slotDefect_triple_bound gs f hf hsig B hgs t r p (hsub t t.property) (hsub r r.property) (hsub p p.property) (hne' t r h₂.symm) (hne' r p h₁.symm) (hne' t p h₃.symm)) refine ⟨p.val,p.property,?_⟩ intro r hr hpr exact hp ⟨r,hr⟩ (fun h => hpr (congrArg Subtype.val h)) end IndexedSlotCoefficients section VarianceTree open scoped BigOperators Classical variable {ι : Type*} [sectionInstance34 : Fintype ι] [sectionInstance35 : DecidableEq ι] noncomputable def slotVariance (ps : List (ι × ι)) (f H : Set ι → ℝ) (A : Set ι) : ℝ := slotTotal ps (fun S => f S*(H S)^2) A - (slotTotal ps (fun S => f S*H S) A)^2 / slotTotal ps f A lemma slotVariance_nil (f H : Set ι → ℝ) (A : Set ι) (_ : f A ≠ 0) : slotVariance [] f H A = 0 := by unfold slotVariance simp only [slotTotal_nil] field_simp ; ring lemma slotVariance_perm {ps qs : List (ι × ι)} (h : ps.Perm qs) (f H : Set ι → ℝ) (A : Set ι) : slotVariance ps f H A = slotVariance qs f H A := by unfold slotVariance rw [slotTotal_perm h, slotTotal_perm h, slotTotal_perm h] lemma variance_split_algebra (a b x y u v : ℝ) (ha : 0 < a) (hb : 0 < b) : x+y-(u+v)^2/(a+b) = (x-u^2/a) + (y-v^2/b) + a*b/(a+b)*(u/a-v/b)^2 := by have hab : a+b ≠ 0 := ne_of_gt (add_pos ha hb) field_simp ; ring lemma slotVariance_split (ps : List (ι × ι)) (f H : Set ι → ℝ) (hf : ∀ S, 0 < f S) (A : Set ι) (p : ι × ι) (hps : SlotsFresh (p::ps) A) : slotVariance (p::ps) f H A = slotVariance ps f H (insert p.1 A) + slotVariance ps f H (insert p.2 A) + (slotTotal ps f (insert p.1 A)*slotTotal ps f (insert p.2 A) / slotTotal (p::ps) f A)* (slotTotal ps (fun S => f S*H S) (insert p.1 A)/slotTotal ps f (insert p.1 A) - slotTotal ps (fun S => f S*H S) (insert p.2 A)/slotTotal ps f (insert p.2 A))^2 := by unfold slotVariance simp only [slotTotal_cons p ps _ A hps.1 hps.2.1 hps.2.2.1] apply variance_split_algebra · exact slotTotal_pos ps f hf _ (hps.2.2.2.mono (by intro x hx; simp only [Set.mem_insert_iff] at hx ⊢; tauto)) · exact slotTotal_pos ps f hf _ (hps.2.2.2.mono (Set.subset_insert _ _)) lemma slotVariance_nonneg (ps : List (ι × ι)) (f H : Set ι → ℝ) (hf : ∀ S, 0 < f S) (A : Set ι) (hps : SlotsFresh ps A) : 0 ≤ slotVariance ps f H A := by induction ps generalizing A with | nil => rw [slotVariance_nil f H A (ne_of_gt (hf A))] | cons p ps ih => have h₁ : SlotsFresh ps (insert p.1 A) := hps.2.2.2.mono (by intro x hx; simp only [Set.mem_insert_iff] at hx ⊢; tauto) have h₂ : SlotsFresh ps (insert p.2 A) := hps.2.2.2.mono (Set.subset_insert _ _) rw [slotVariance_split ps f H hf A p hps] exact add_nonneg (add_nonneg (ih _ h₁) (ih _ h₂)) (mul_nonneg (div_nonneg (mul_nonneg (slotTotal_pos ps f hf _ h₁).le (slotTotal_pos ps f hf _ h₂).le) (slotTotal_pos _ f hf _ hps).le) (sq_nonneg _)) omit sectionInstance34 sectionInstance35 in lemma slotPunctures_length [Fintype ι] [DecidableEq ι] (ps : List (ι × ι)) : (slotPunctures ps).length = ps.length := by induction ps with | nil => rfl | cons p ps ih => simp only [slotPunctures, List.length_cons,List.length_map,ih] lemma list_sum_map_le_const {β : Type*} (l : List β) (g : β → ℝ) (C : ℝ) (h : ∀ x ∈ l, g x ≤ C) : (l.map g).sum ≤ (l.length : ℝ)*C := by induction l with | nil => simp | cons x l ih => simp only [List.map_cons,List.sum_cons,List.length_cons,Nat.cast_add,Nat.cast_one] have hh := ih (fun y hy => h y (List.mem_cons_of_mem _ hy)) have hx := h x (List.mem_cons_self) linarith theorem transport_node_variance (ps : List (ι × ι)) (f H : Set ι → ℝ) (A : Set ι) (p d : ι) (W : ι → ℝ) (hf : ∀ S, 0 < f S) (hSig : HasSlotSignature f) (hpd : p ≠ d) (hpA : p ∉ A) (hdA : d ∉ A) (hps : SlotsFresh ps (A ∪ Set.range (rootEmbedding p d))) (hW : ∀ i, 0 < W i) (hw : ∀ p ∈ ps, W p.1 = W p.2) (hWp : W p = 1) (hWd : W d = 1) (hsink : ∀ x ∈ slotPunctures ps, slotTotal x.2 f (insert p (insert d A))/W x.1.1 ≤ 4*(slotTotal ps f (insert p A)+slotTotal ps f (insert d A))) : let sp := slotTotal ps f (insert p A) let sd := slotTotal ps f (insert d A) sp*sd/(sp+sd) * (slotTotal ps (fun S => f S*H S) (insert p A)/sp - slotTotal ps (fun S => f S*H S) (insert d A)/sd)^2 ≤ (1+8*(ps.length : ℝ))*slotGraphEnergy ps f H A (rootEmbedding p d) W := by let sp := slotTotal ps f (insert p A) let sd := slotTotal ps f (insert d A) have hp : 0 < sp := slotTotal_pos ps f hf _ (hps.mono (by intro x hx; rcases hx with rfl | hx · exact Or.inr ⟨false,rfl⟩ · exact Or.inl hx)) have hd : 0 < sd := slotTotal_pos ps f hf _ (hps.mono (by intro x hx; rcases hx with rfl | hx · exact Or.inr ⟨true,rfl⟩ · exact Or.inl hx)) have hpd' : 0 < sp*sd/(sp+sd) := div_pos (mul_pos hp hd) (add_pos hp hd) have hsum := list_sum_map_le_const (slotPunctures ps) (fun x => slotTotal x.2 f (insert p (insert d A))/W x.1.1) (4*(sp+sd)) hsink rw [slotPunctures_length] at hsum have hcoef : sp*sd/(sp+sd)*rootCoefficient ps f A p d W ≤ 1+8*(ps.length : ℝ) := by unfold rootCoefficient change sp*sd/(sp+sd)*(1/(sp*W p)+1/(sd*W d)+2/(sp*sd)*_) ≤ _ rw [hWp,hWd,mul_one,mul_one] have heq (s : ℝ) : sp*sd/(sp+sd)*(1/sp+1/sd+2/(sp*sd)*s) = 1+2/(sp+sd)*s := by field_simp ; ring rw [heq] have hh := mul_le_mul_of_nonneg_left hsum (show 0 ≤ 2/(sp+sd) by positivity) have heq' : 2/(sp+sd)*((ps.length : ℝ)*(4*(sp+sd))) = 8*(ps.length : ℝ) := by field_simp ; ring rw [heq'] at hh linarith have hE : 0 ≤ slotGraphEnergy ps f H A (rootEmbedding p d) W := by unfold slotGraphEnergy apply div_nonneg _ (by norm_num) apply Finset.sum_nonneg intro ST hST unfold slotEdgeEnergy apply mul_nonneg _ (sq_nonneg _) apply le_min · exact mul_nonneg (missingMultiplier_nonneg ps _ W (fun i => (hW i).le) _ ) (hf _).le · exact mul_nonneg (missingMultiplier_nonneg ps _ W (fun i => (hW i).le) _ ) (hf _).le have ht := mul_le_mul_of_nonneg_left (transport_graph_bound ps f H A p d W hf hSig hpd hpA hdA hps hW hw) hpd'.le dsimp only exact ht.trans (by rw [← mul_assoc]; exact mul_le_mul_of_nonneg_right hcoef hE) end VarianceTree section StateGeometry open scoped BigOperators Classical variable {Γ : Type*} [sectionInstance36 : Fintype Γ] [sectionInstance37 : DecidableEq Γ] def PairSingle (p : Γ × Γ) (S : Set Γ) : Prop := (p.1 ∈ S ∧ p.2 ∉ S) ∨ (p.2 ∈ S ∧ p.1 ∉ S) def PairFull (p : Γ × Γ) (S : Set Γ) : Prop := p.1 ∈ S ∧ p.2 ∈ S def PairEmpty (p : Γ × Γ) (S : Set Γ) : Prop := p.1 ∉ S ∧ p.2 ∉ S omit sectionInstance36 sectionInstance37 in lemma PairSingle.not_full [Fintype Γ] [DecidableEq Γ] {p : Γ × Γ} {S : Set Γ} (h : PairSingle p S) : ¬ PairFull p S := by unfold PairSingle PairFull at * tauto omit sectionInstance36 sectionInstance37 in lemma PairSingle.not_empty [Fintype Γ] [DecidableEq Γ] {p : Γ × Γ} {S : Set Γ} (h : PairSingle p S) : ¬ PairEmpty p S := by unfold PairSingle PairEmpty at * tauto omit sectionInstance36 sectionInstance37 in lemma PairFull.not_empty [Fintype Γ] [DecidableEq Γ] {p : Γ × Γ} {S : Set Γ} (h : PairFull p S) : ¬ PairEmpty p S := by unfold PairFull PairEmpty at * tauto def PlainState (gs : List (Γ × Γ)) (S : Set Γ) : Prop := ∀ p ∈ gs, PairSingle p S def DefectState (gs : List (Γ × Γ)) (p r : Γ × Γ) (S : Set Γ) : Prop := p ∈ gs ∧ r ∈ gs ∧ p ≠ r ∧ PairEmpty p S ∧ PairFull r S ∧ ∀ t ∈ gs, t ≠ p → t ≠ r → PairSingle t S lemma DefectState.not_plain {gs : List (Γ × Γ)} {p r : Γ × Γ} {S : Set Γ} (h : DefectState gs p r S) : ¬ PlainState gs S := by intro hs exact (hs p h.1).not_empty h.2.2.2.1 lemma DefectState.unique {gs : List (Γ × Γ)} {p r p' r' : Γ × Γ} {S : Set Γ} (h : DefectState gs p r S) (h' : DefectState gs p' r' S) : p = p' ∧ r = r' := by obtain ⟨hp,hr,hpr,hep,hfr,hs⟩ := h obtain ⟨hp',hr',hpr',hep',hfr',hs'⟩ := h' have hpp : p = p' := by by_contra hne by_cases hpr' : p = r' · subst r'; exact hfr'.not_empty hep · exact (hs' p hp hne hpr').not_empty hep subst p' refine ⟨rfl,?_⟩ by_contra hne exact (hs' r hr hpr.symm hne).not_full hfr omit sectionInstance36 sectionInstance37 in lemma SlotsFresh.elements_fresh [Fintype Γ] [DecidableEq Γ] {ps : List (Γ × Γ)} {A : Set Γ} (h : SlotsFresh ps A) (p : Γ × Γ) (hp : p ∈ ps) : p.1 ∉ A ∧ p.2 ∉ A := by induction ps generalizing A with | nil => simp at hp | cons q ps ih => rcases List.mem_cons.mp hp with rfl | hp · exact ⟨h.2.1,h.2.2.1⟩ · have hh := ih h.2.2.2 hp exact ⟨fun hx => hh.1 (Or.inr (Or.inr hx)), fun hx => hh.2 (Or.inr (Or.inr hx))⟩ lemma SlotsFresh.pair_ne_of_mem {ps : List (Γ × Γ)} {A : Set Γ} {p : Γ × Γ} (h : SlotsFresh (p::ps) A) {r : Γ × Γ} (hr : r ∈ ps) : p ≠ r := by intro heq subst r exact (h.2.2.2.elements_fresh p hr).1 (Set.mem_insert _ _) lemma SlotsFresh.nodup {ps : List (Γ × Γ)} {A : Set Γ} (h : SlotsFresh ps A) : ps.Nodup := by induction ps generalizing A with | nil => exact List.nodup_nil | cons p ps ih => exact List.nodup_cons.mpr ⟨fun hp => (h.pair_ne_of_mem hp) rfl,ih h.2.2.2⟩ omit sectionInstance36 sectionInstance37 in lemma slotVertices_fixed [Fintype Γ] [DecidableEq Γ] (ps : List (Γ × Γ)) : ∀ {J : Type*} [Fintype J] (A : Set Γ) (e : J → Γ) (S : Set Γ), S ∈ slotVertices ps A e → A ⊆ S := by induction ps with | nil => intro J _ A e S h rw [slotVertices] at h obtain ⟨j,_,rfl⟩ := Finset.mem_image.mp h exact Set.subset_insert _ _ | cons p ps ih => intro J _ A e S h rw [slotVertices] at h rcases Finset.mem_union.mp h with h | h · exact (Set.subset_insert _ _).trans (ih _ _ _ h) · exact (Set.subset_insert _ _).trans (ih _ _ _ h) lemma slotVertices_classify (ps : List (Γ × Γ)) : ∀ {J : Type*} [Fintype J] [DecidableEq J] (A : Set Γ) (e : J → Γ), Function.Injective e → (∀ j, e j ∉ A) → SlotsFresh ps (A ∪ Set.range e) → ∀ S ∈ slotVertices ps A e, (∃ j, (∀ i, e i ∈ S ↔ i = j) ∧ ∀ p ∈ ps, PairSingle p S) ∨ (∃ p ∈ ps, (∀ i, e i ∉ S) ∧ PairFull p S ∧ ∀ r ∈ ps, r ≠ p → PairSingle r S) := by induction ps with | nil => intro J _ _ A e he heA _ S h rw [slotVertices] at h obtain ⟨j,_,rfl⟩ := Finset.mem_image.mp h left refine ⟨j,fun i => ?_,by simp⟩ simp only [Set.mem_insert_iff, heA i, or_false] exact he.eq_iff | cons p ps ih => intro J _ _ A e he heA hps S h have hab := hps.1 have ha := hps.2.1 have hb := hps.2.2.1 obtain ⟨hfa,hfb⟩ := slotsFresh_child e A p ps hps have branch (a b : Γ) (hab : a ≠ b) (haA : a ∉ A) (hbE : b ∉ Set.range e) (haE : a ∉ Set.range e) (hf : SlotsFresh ps (insert b A ∪ Set.range (appendPoint e a))) (hm : S ∈ slotVertices ps (insert b A) (appendPoint e a)) : (∃ j, (∀ i, e i ∈ S ↔ i = j) ∧ PairSingle (a,b) S ∧ ∀ r ∈ ps, PairSingle r S) ∨ ((∀ i, e i ∉ S) ∧ PairFull (a,b) S ∧ ∀ r ∈ ps, PairSingle r S) ∨ (∃ r ∈ ps, (∀ i, e i ∉ S) ∧ PairFull r S ∧ PairSingle (a,b) S ∧ ∀ t ∈ ps, t ≠ r → PairSingle t S) := by have hbS : b ∈ S := slotVertices_fixed ps _ _ S hm (Set.mem_insert _ _) have hh := ih (insert b A) (appendPoint e a) (appendPoint_injective e a he haE) (appendPoint_fresh e A a b heA hab haA hbE) hf S hm rcases hh with ⟨j,hj,hr⟩ | ⟨r,hr,he',hfull,hrest⟩ · cases j with | none => right; left refine ⟨fun i hi => ?_,⟨?_,hbS⟩,hr⟩ · exact Option.some_ne_none i ((hj (some i)).mp hi) · exact (hj none).mpr rfl | some j => left refine ⟨j,fun i => ?_,Or.inr ⟨hbS,?_⟩,hr⟩ · simpa only [appendPoint, Option.some.injEq] using hj (some i) · intro haS; exact Option.some_ne_none j (((hj none).mp haS).symm) · right; right exact ⟨r,hr,fun i => he' (some i),hfull,Or.inr ⟨hbS,he' none⟩,hrest⟩ rw [slotVertices] at h rcases Finset.mem_union.mp h with h | h · have hh := branch p.1 p.2 hab (fun h => ha (Or.inl h)) (fun h => hb (Or.inr h)) (fun h => ha (Or.inr h)) hfa h rcases hh with ⟨j,hj,hp,hr⟩ | ⟨hi,hp,hr⟩ | ⟨r,hr,hi,hfull,hp,hrest⟩ · left; exact ⟨j,hj,fun r hr' => (List.mem_cons.mp hr').elim (fun heq => heq ▸ hp) (hr r)⟩ · right refine ⟨p,List.mem_cons_self,hi,hp,?_⟩ intro r hr' hne exact hr r ((List.mem_cons.mp hr').resolve_left hne) · right refine ⟨r,List.mem_cons_of_mem _ hr,hi,hfull,?_⟩ intro t ht hne rcases List.mem_cons.mp ht with rfl | ht · exact hp · exact hrest t ht hne · have hh := branch p.2 p.1 hab.symm (fun h => hb (Or.inl h)) (fun h => ha (Or.inr h)) (fun h => hb (Or.inr h)) hfb h have hsingle : PairSingle (p.2,p.1) S → PairSingle p S := fun h => h.elim Or.inr Or.inl have hfull : PairFull (p.2,p.1) S → PairFull p S := And.symm rcases hh with ⟨j,hj,hp,hr⟩ | ⟨hi,hp,hr⟩ | ⟨r,hr,hi,hfr,hp,hrest⟩ · left; exact ⟨j,hj,fun r hr' => (List.mem_cons.mp hr').elim (fun heq => heq ▸ hsingle hp) (hr r)⟩ · right refine ⟨p,List.mem_cons_self,hi,hfull hp,?_⟩ intro r hr' hne exact hr r ((List.mem_cons.mp hr').resolve_left hne) · right refine ⟨r,List.mem_cons_of_mem _ hr,hi,hfr,?_⟩ intro t ht hne rcases List.mem_cons.mp ht with rfl | ht · exact hsingle hp · exact hrest t ht hne end StateGeometry section RestrictedEnergy open scoped BigOperators Classical variable {Γ : Type*} [sectionInstance38 : Fintype Γ] [sectionInstance39 : DecidableEq Γ] def Respects (A B S : Set Γ) : Prop := A ⊆ S ∧ Disjoint B S def EdgeRespects (A B : Set Γ) (ST : Set Γ × Set Γ) : Prop := Respects A B ST.1 ∧ Respects A B ST.2 noncomputable def restrictedEnergy (E : Finset (Set Γ × Set Γ)) (c : (Set Γ × Set Γ) → ℝ) (H : Set Γ → ℝ) (A B : Set Γ) : ℝ := (∑ ST ∈ E, if EdgeRespects A B ST then c ST*(H ST.1-H ST.2)^2 else 0)/2 omit sectionInstance38 sectionInstance39 in lemma Respects.parent [Fintype Γ] [DecidableEq Γ] {A B S : Set Γ} {a b : Γ} (h : Respects (insert a A) (insert b B) S) : Respects A B S := ⟨(Set.subset_insert _ _).trans h.1, h.2.mono_left (Set.subset_insert _ _)⟩ omit sectionInstance38 sectionInstance39 in lemma Respects.child_disjoint [Fintype Γ] [DecidableEq Γ] {A B S : Set Γ} {a b : Γ} (h : Respects (insert a A) (insert b B) S) : ¬ Respects (insert b A) (insert a B) S := by intro h' exact Set.disjoint_left.mp h'.2 (Set.mem_insert _ _) (h.1 (Set.mem_insert _ _)) omit sectionInstance38 sectionInstance39 in lemma restrictedEnergy_nonneg [Fintype Γ] [DecidableEq Γ] (E : Finset (Set Γ × Set Γ)) (c : (Set Γ × Set Γ) → ℝ) (H : Set Γ → ℝ) (A B : Set Γ) (hc : ∀ ST ∈ E, 0 ≤ c ST) : 0 ≤ restrictedEnergy E c H A B := by apply div_nonneg _ (by norm_num) apply Finset.sum_nonneg intro ST hST split_ifs · exact mul_nonneg (hc ST hST) (sq_nonneg _) · rfl lemma restrictedEnergy_children (E : Finset (Set Γ × Set Γ)) (c : (Set Γ × Set Γ) → ℝ) (H : Set Γ → ℝ) (A B : Set Γ) (a b : Γ) (hc : ∀ ST ∈ E, 0 ≤ c ST) : restrictedEnergy E c H (insert a A) (insert b B) + restrictedEnergy E c H (insert b A) (insert a B) ≤ restrictedEnergy E c H A B := by unfold restrictedEnergy rw [← add_div, ← Finset.sum_add_distrib] apply div_le_div_of_nonneg_right _ (by norm_num) apply Finset.sum_le_sum intro ST hST have hw : 0 ≤ c ST*(H ST.1-H ST.2)^2 := mul_nonneg (hc ST hST) (sq_nonneg _) by_cases h₁ : EdgeRespects (insert a A) (insert b B) ST · have hp : EdgeRespects A B ST := ⟨h₁.1.parent,h₁.2.parent⟩ have hn : ¬ EdgeRespects (insert b A) (insert a B) ST := fun h₂ => h₁.1.child_disjoint h₂.1 simp only [ite_eq_left h₁,ite_eq_right hn,ite_eq_left hp,add_zero,le_refl] · by_cases h₂ : EdgeRespects (insert b A) (insert a B) ST · have hp : EdgeRespects A B ST := ⟨h₂.1.parent,h₂.2.parent⟩ simp only [ite_eq_right h₁,ite_eq_left h₂,ite_eq_left hp,zero_add,le_refl] · simp only [ite_eq_right h₁,ite_eq_right h₂,zero_add] split_ifs <;> positivity theorem adaptive_variance_bound (f H : Set Γ → ℝ) (hf : ∀ S, 0 < f S) (E : Finset (Set Γ × Set Γ)) (c : (Set Γ × Set Γ) → ℝ) (hc : ∀ ST ∈ E, 0 ≤ c ST) (C : ℝ) (hC : 0 ≤ C) (P : List (Γ × Γ) → Set Γ → Set Γ → Prop) (hchoose : ∀ ps A B, P ps A B → ps ≠ [] → ∃ p qs, ps.Perm (p::qs) ∧ SlotsFresh (p::qs) A ∧ P qs (insert p.1 A) (insert p.2 B) ∧ P qs (insert p.2 A) (insert p.1 B) ∧ slotVariance (p::qs) f H A - slotVariance qs f H (insert p.1 A) - slotVariance qs f H (insert p.2 A) ≤ C*restrictedEnergy E c H A B) : ∀ ps A B, P ps A B → slotVariance ps f H A ≤ (ps.length : ℝ)*C*restrictedEnergy E c H A B := by intro ps induction hn : ps.length using Nat.strong_induction_on generalizing ps with | h n ih => intro A B hP by_cases hnil : ps = [] · subst ps have hn0 : n = 0 := hn.symm subst n simp only [slotVariance_nil f H A (ne_of_gt (hf A)),List.length_nil,Nat.cast_zero,zero_mul,le_refl] · obtain ⟨p,qs,hperm,hfresh,hP₁,hP₂,hnode⟩ := hchoose ps A B hP hnil have hpq : ps.length = qs.length+1 := by simpa using hperm.length_eq have hq : qs.length < n := by omega have ha := ih qs.length hq qs rfl (insert p.1 A) (insert p.2 B) hP₁ have hb := ih qs.length hq qs rfl (insert p.2 A) (insert p.1 B) hP₂ have he := restrictedEnergy_children E c H A B p.1 p.2 hc have hmul := mul_le_mul_of_nonneg_left he (mul_nonneg (Nat.cast_nonneg qs.length) hC) rw [← hn, slotVariance_perm hperm f H A,hpq,Nat.cast_add,Nat.cast_one] nlinarith end RestrictedEnergy section ChainIdentification open scoped BigOperators Classical variable {Γ : Type*} [sectionInstance40 : Fintype Γ] [sectionInstance41 : DecidableEq Γ] omit sectionInstance40 sectionInstance41 in lemma slotVertices_excluded [Fintype Γ] [DecidableEq Γ] (ps : List (Γ × Γ)) : ∀ {J : Type*} [Fintype J] (A B : Set Γ) (e : J → Γ), Disjoint A B → (∀ j, e j ∉ B) → (∀ p ∈ ps, p.1 ∉ B ∧ p.2 ∉ B) → ∀ S ∈ slotVertices ps A e, Disjoint B S := by induction ps with | nil => intro J _ A B e hAB he _ S hS rw [slotVertices] at hS obtain ⟨j,_,rfl⟩ := Finset.mem_image.mp hS exact Set.disjoint_insert_right.mpr ⟨he j,hAB.symm⟩ | cons p ps ih => intro J _ A B e hAB he hp S hS obtain ⟨hp₁,hp₂⟩ := hp p List.mem_cons_self have hrest := fun r hr => hp r (List.mem_cons_of_mem _ hr) rw [slotVertices] at hS rcases Finset.mem_union.mp hS with hS | hS · apply ih (insert p.2 A) B (appendPoint e p.1) (Set.disjoint_insert_left.mpr ⟨hp₂,hAB⟩) _ hrest S hS intro j; cases j <;> first | exact hp₁ | exact he _ · apply ih (insert p.1 A) B (appendPoint e p.2) (Set.disjoint_insert_left.mpr ⟨hp₁,hAB⟩) _ hrest S hS intro j; cases j <;> first | exact hp₂ | exact he _ def FixedOutside (gs ps : List (Γ × Γ)) (A B : Set Γ) : Prop := ∀ r ∈ gs, r ∉ ps → (r.1 ∈ A ∧ r.2 ∈ B) ∨ (r.2 ∈ A ∧ r.1 ∈ B) omit sectionInstance40 sectionInstance41 in lemma FixedOutside.single [Fintype Γ] [DecidableEq Γ] {gs ps : List (Γ × Γ)} {A B S : Set Γ} (h : FixedOutside gs ps A B) (hS : Respects A B S) (r : Γ × Γ) (hr : r ∈ gs) (hn : r ∉ ps) : PairSingle r S := by rcases h r hr hn with h | h · exact Or.inl ⟨hS.1 h.1,fun hx => Set.disjoint_left.mp hS.2 h.2 hx⟩ · exact Or.inr ⟨hS.1 h.1,fun hx => Set.disjoint_left.mp hS.2 h.2 hx⟩ noncomputable def chainMultiplier (gs : List (Γ × Γ)) (w : (Γ × Γ) → (Γ × Γ) → ℝ) (S : Set Γ) : ℝ := if h : ∃ p r, DefectState gs p r S then w h.choose h.choose_spec.choose else 1 lemma chainMultiplier_plain (gs : List (Γ × Γ)) (w : (Γ × Γ) → (Γ × Γ) → ℝ) (S : Set Γ) (h : PlainState gs S) : chainMultiplier gs w S = 1 := by unfold chainMultiplier rw [dite_eq_right] rintro ⟨p,r,hpr⟩ exact hpr.not_plain h lemma chainMultiplier_defect (gs : List (Γ × Γ)) (w : (Γ × Γ) → (Γ × Γ) → ℝ) (S : Set Γ) {p r : Γ × Γ} (h : DefectState gs p r S) : chainMultiplier gs w S = w p r := by have he : ∃ p r, DefectState gs p r S := ⟨p,r,h⟩ unfold chainMultiplier rw [dite_eq_left he] have hh := he.choose_spec.choose_spec.unique h exact congrArg₂ w hh.1 hh.2 omit sectionInstance41 in lemma chainMultiplier_pos [DecidableEq Γ] (gs : List (Γ × Γ)) (w : (Γ × Γ) → (Γ × Γ) → ℝ) (hw : ∀ p r, 0 < w p r) (S : Set Γ) : 0 < chainMultiplier gs w S := by unfold chainMultiplier split_ifs <;> first | exact hw _ _ | norm_num def ChainState (gs : List (Γ × Γ)) (S : Set Γ) : Prop := PlainState gs S ∨ ∃ p r, DefectState gs p r S noncomputable def chainEdges (gs : List (Γ × Γ)) : Finset (Set Γ × Set Γ) := Finset.univ.filter (fun ST => ChainState gs ST.1 ∧ ChainState gs ST.2 ∧ ExchangeAdjacent ST.1 ST.2) noncomputable def chainConductance (gs : List (Γ × Γ)) (w : (Γ × Γ) → (Γ × Γ) → ℝ) (f : Set Γ → ℝ) (ST : Set Γ × Set Γ) : ℝ := min (chainMultiplier gs w ST.1*f ST.1) (chainMultiplier gs w ST.2*f ST.2) lemma list_sum_single {β : Type*} [DecidableEq β] (ps : List β) (hn : ps.Nodup) (p : β) (hp : p ∈ ps) (g : β → ℝ) (hg : ∀ r ∈ ps, r ≠ p → g r = 0) : (ps.map g).sum = g p := by rw [← List.sum_toFinset _ hn] exact Finset.sum_eq_single p (fun b hb hbp => hg b (List.mem_toFinset.mp hb) hbp) (fun hn => False.elim (hn (List.mem_toFinset.mpr hp))) lemma missingMultiplier_old {J : Type*} [Fintype J] [DecidableEq J] (ps : List (Γ × Γ)) (e : J → Γ) (W : Γ → ℝ) (S : Set Γ) (j : J) (hj : ∀ i, e i ∈ S ↔ i = j) (hp : ∀ p ∈ ps, PairSingle p S) : missingMultiplier ps e W S = W (e j) := by unfold missingMultiplier have hz : (ps.map (fun p => if p.1 ∈ S ∧ p.2 ∈ S then W p.1 else 0)).sum = 0 := by apply List.sum_eq_zero intro x hx obtain ⟨p,hp',rfl⟩ := List.mem_map.mp hx exact ite_eq_right (hp p hp').not_full rw [hz,add_zero] simp only [hj] simp lemma missingMultiplier_new {J : Type*} [Fintype J] (ps : List (Γ × Γ)) (hn : ps.Nodup) (e : J → Γ) (W : Γ → ℝ) (S : Set Γ) (p : Γ × Γ) (hp : p ∈ ps) (he : ∀ i, e i ∉ S) (hf : PairFull p S) (hr : ∀ r ∈ ps, r ≠ p → PairSingle r S) : missingMultiplier ps e W S = W p.1 := by unfold missingMultiplier simp only [he,ite_false,Finset.sum_const_zero,zero_add] have hh := list_sum_single ps hn p hp (fun r => if r.1 ∈ S ∧ r.2 ∈ S then W r.1 else 0) (fun r hr' hne => ite_eq_right (hr r hr' hne).not_full) exact hh.trans (ite_eq_left hf) lemma SlotsFresh.pair_contains_unique {ps : List (Γ × Γ)} {A : Set Γ} (h : SlotsFresh ps A) {p r : Γ × Γ} (hp : p ∈ ps) (hr : r ∈ ps) {x : Γ} (hxp : x = p.1 ∨ x = p.2) (hxr : x = r.1 ∨ x = r.2) : p = r := by by_contra hne have hh := (SlotsFresh.perm (slots_perm_two hp hr hne) A).mp h have hr₁ := hh.2.2.2.2.1 have hr₂ := hh.2.2.2.2.2.1 rcases hxp with rfl | rfl <;> rcases hxr with heq | heq · exact hr₁ (Or.inl heq.symm) · exact hr₂ (Or.inl heq.symm) · exact hr₁ (Or.inr (Or.inl heq.symm)) · exact hr₂ (Or.inr (Or.inl heq.symm)) noncomputable def pairMultiplier (ps : List (Γ × Γ)) (w : (Γ × Γ) → ℝ) (x : Γ) : ℝ := if h : ∃ p ∈ ps, x = p.1 ∨ x = p.2 then w h.choose else 1 omit sectionInstance40 in lemma pairMultiplier_pos [Fintype Γ] (ps : List (Γ × Γ)) (w : (Γ × Γ) → ℝ) (hw : ∀ p, 0 < w p) (x : Γ) : 0 < pairMultiplier ps w x := by unfold pairMultiplier split_ifs <;> first | exact hw _ | norm_num lemma pairMultiplier_on {ps : List (Γ × Γ)} {A : Set Γ} (hps : SlotsFresh ps A) (w : (Γ × Γ) → ℝ) (p : Γ × Γ) (hp : p ∈ ps) (x : Γ) (hx : x = p.1 ∨ x = p.2) : pairMultiplier ps w x = w p := by have he : ∃ p ∈ ps, x = p.1 ∨ x = p.2 := ⟨p,hp,hx⟩ unfold pairMultiplier rw [dite_eq_left he] rw [hps.pair_contains_unique he.choose_spec.1 hp he.choose_spec.2 hx] lemma pairMultiplier_fresh {ps : List (Γ × Γ)} {A : Set Γ} (hps : SlotsFresh ps A) (w : (Γ × Γ) → ℝ) (x : Γ) (hx : x ∈ A) : pairMultiplier ps w x = 1 := by unfold pairMultiplier rw [dite_eq_right] rintro ⟨p,hp,h⟩ rcases h with rfl | rfl · exact (hps.elements_fresh p hp).1 hx · exact (hps.elements_fresh p hp).2 hx lemma variance_vertex_identification (gs ps : List (Γ × Γ)) (A B : Set Γ) (p : Γ × Γ) (w : (Γ × Γ) → (Γ × Γ) → ℝ) (hsub : ∀ r ∈ p::ps, r ∈ gs) (hAB : Disjoint A B) (hfresh : SlotsFresh (p::ps) (A ∪ B)) (hout : FixedOutside gs (p::ps) A B) (S : Set Γ) (hS : S ∈ slotVertices ps A (rootEmbedding p.1 p.2)) : ChainState gs S ∧ Respects A B S ∧ missingMultiplier ps (rootEmbedding p.1 p.2) (pairMultiplier ps (w p)) S = chainMultiplier gs w S := by have hps : SlotsFresh ps (A ∪ Set.range (rootEmbedding p.1 p.2)) := hfresh.2.2.2.mono (by intro x hx rcases hx with hx | ⟨i,rfl⟩ · exact Or.inr (Or.inr (Or.inl hx)) · cases i <;> simp [rootEmbedding]) have heA : ∀ j, rootEmbedding p.1 p.2 j ∉ A := by intro j; cases j <;> first | exact fun h => hfresh.2.1 (Or.inl h) | exact fun h => hfresh.2.2.1 (Or.inl h) have heB : ∀ j, rootEmbedding p.1 p.2 j ∉ B := by intro j; cases j <;> first | exact fun h => hfresh.2.1 (Or.inr h) | exact fun h => hfresh.2.2.1 (Or.inr h) have hSB : Disjoint B S := slotVertices_excluded ps A B _ hAB heB (fun r hr => let hh := hfresh.elements_fresh r (List.mem_cons_of_mem _ hr) ⟨fun h => hh.1 (Or.inr h),fun h => hh.2 (Or.inr h)⟩) S hS have hrespect : Respects A B S := ⟨slotVertices_fixed ps A _ S hS,hSB⟩ have hclass := slotVertices_classify ps A _ (rootEmbedding_injective _ _ hfresh.1) heA hps S hS rcases hclass with ⟨j,hj,hrest⟩ | ⟨r,hr,he,hfull,hrest⟩ · have hp : PairSingle p S := by cases j · exact Or.inl ⟨(hj false).mpr rfl,fun h => Bool.noConfusion ((hj true).mp h)⟩ · exact Or.inr ⟨(hj true).mpr rfl,fun h => Bool.noConfusion ((hj false).mp h)⟩ have hplain : PlainState gs S := by intro r hr by_cases hm : r ∈ p::ps · rcases List.mem_cons.mp hm with rfl | hm · exact hp · exact hrest r hm · exact hout.single hrespect r hr hm refine ⟨Or.inl hplain,hrespect,?_⟩ rw [chainMultiplier_plain gs w S hplain,missingMultiplier_old ps _ _ S j hj hrest] exact pairMultiplier_fresh hps _ _ (Or.inr ⟨j,rfl⟩) · have hdef : DefectState gs p r S := by refine ⟨hsub p List.mem_cons_self,hsub r (List.mem_cons_of_mem _ hr), hfresh.pair_ne_of_mem hr,⟨he false,he true⟩,hfull,?_⟩ intro t ht htp htr by_cases hm : t ∈ p::ps · exact hrest t ((List.mem_cons.mp hm).resolve_left htp) htr · exact hout.single hrespect t ht hm refine ⟨Or.inr ⟨p,r,hdef⟩,hrespect,?_⟩ rw [chainMultiplier_defect gs w S hdef, missingMultiplier_new ps hps.nodup _ _ S r hr he hfull hrest] exact pairMultiplier_on hps _ r hr r.1 (Or.inl rfl) lemma variance_energy_identification (gs ps : List (Γ × Γ)) (A B : Set Γ) (p : Γ × Γ) (w : (Γ × Γ) → (Γ × Γ) → ℝ) (f H : Set Γ → ℝ) (hw : ∀ p r, 0 < w p r) (hf : ∀ S, 0 < f S) (hsub : ∀ r ∈ p::ps, r ∈ gs) (hAB : Disjoint A B) (hfresh : SlotsFresh (p::ps) (A ∪ B)) (hout : FixedOutside gs (p::ps) A B) : slotGraphEnergy ps f H A (rootEmbedding p.1 p.2) (pairMultiplier ps (w p)) ≤ restrictedEnergy (chainEdges gs) (chainConductance gs w f) H A B := by have hvertex := variance_vertex_identification gs ps A B p w hsub hAB hfresh hout unfold slotGraphEnergy restrictedEnergy apply div_le_div_of_nonneg_right _ (by norm_num) let D := slotGraphEdges ps A (rootEmbedding p.1 p.2) have hE : D ⊆ chainEdges gs := by intro ST hST obtain ⟨hprod,hadj⟩ := Finset.mem_filter.mp hST obtain ⟨hs,ht⟩ := Finset.mem_product.mp hprod exact Finset.mem_filter.mpr ⟨Finset.mem_univ _,(hvertex ST.1 hs).1,(hvertex ST.2 ht).1,hadj⟩ calc _ = ∑ ST ∈ D, if EdgeRespects A B ST then chainConductance gs w f ST*(H ST.1-H ST.2)^2 else 0 := by apply Finset.sum_congr rfl intro ST hST obtain ⟨hs,ht⟩ := Finset.mem_product.mp (Finset.mem_filter.mp hST).1 have hs' := hvertex ST.1 hs have ht' := hvertex ST.2 ht rw [ite_eq_left (show EdgeRespects A B ST from ⟨hs'.2.1,ht'.2.1⟩)] simp only [slotEdgeEnergy,hs'.2.2,ht'.2.2,chainConductance] _ ≤ _ := by apply Finset.sum_le_sum_of_subset_of_nonneg hE intro ST hST _ split_ifs · exact mul_nonneg (le_min (mul_nonneg (chainMultiplier_pos gs w hw _).le (hf _).le) (mul_nonneg (chainMultiplier_pos gs w hw _).le (hf _).le)) (sq_nonneg _) · rfl end ChainIdentification section TransversalVariance open scoped BigOperators Classical variable {Γ : Type*} [sectionInstance42 : Fintype Γ] [sectionInstance43 : DecidableEq Γ] omit sectionInstance42 sectionInstance43 in lemma slotPunctures_perm [Fintype Γ] [DecidableEq Γ] (ps : List (Γ × Γ)) (x : (Γ × Γ) × List (Γ × Γ)) (hx : x ∈ slotPunctures ps) : ps.Perm (x.1::x.2) := by induction ps generalizing x with | nil => simp [slotPunctures] at hx | cons p ps ih => rw [slotPunctures,List.mem_cons] at hx rcases hx with rfl | hx · exact List.Perm.refl _ · obtain ⟨y,hy,rfl⟩ := List.mem_map.mp hx exact ((ih y hy).cons p).trans (List.Perm.swap _ _ _) lemma slotDefect_puncture (ps : List (Γ × Γ)) (p : Γ × Γ) (A : Set Γ) (f : Set Γ → ℝ) (hps : SlotsFresh (p::ps) A) (x : (Γ × Γ) × List (Γ × Γ)) (hx : x ∈ slotPunctures ps) : slotDefect (p::ps) f A x.1 p = slotTotal x.2 f (insert p.1 (insert p.2 A)) := by have hperm := slotPunctures_perm ps x hx have hm : x.1 ∈ ps := hperm.mem_iff.mpr List.mem_cons_self rw [slotDefect_perm (hperm.cons p)] simp [slotDefect,hps.pair_ne_of_mem hm] def VarianceNode (gs ps : List (Γ × Γ)) (A B : Set Γ) : Prop := Disjoint A B ∧ SlotsFresh ps (A ∪ B) ∧ (∀ p ∈ ps, p ∈ gs) ∧ FixedOutside gs ps A B lemma VarianceNode.perm {gs ps qs : List (Γ × Γ)} {A B : Set Γ} (h : VarianceNode gs ps A B) (hp : ps.Perm qs) : VarianceNode gs qs A B := by refine ⟨h.1,(SlotsFresh.perm hp _).mp h.2.1,fun r hr => h.2.2.1 r (hp.mem_iff.mpr hr),?_⟩ intro r hr hn exact h.2.2.2 r hr (fun hm => hn (hp.mem_iff.mp hm)) lemma VarianceNode.children {gs ps : List (Γ × Γ)} {A B : Set Γ} {p : Γ × Γ} (h : VarianceNode gs (p::ps) A B) : VarianceNode gs ps (insert p.1 A) (insert p.2 B) ∧ VarianceNode gs ps (insert p.2 A) (insert p.1 B) := by obtain ⟨hAB,hfresh,hsub,hout⟩ := h have hab := hfresh.1 have haA : p.1 ∉ A := fun hx => hfresh.2.1 (Or.inl hx) have haB : p.1 ∉ B := fun hx => hfresh.2.1 (Or.inr hx) have hbA : p.2 ∉ A := fun hx => hfresh.2.2.1 (Or.inl hx) have hbB : p.2 ∉ B := fun hx => hfresh.2.2.1 (Or.inr hx) have ho (a b : Γ) (hp : (a,b) = p ∨ (a,b) = (p.2,p.1)) : FixedOutside gs ps (insert a A) (insert b B) := by intro r hr hn by_cases hrp : r = p · subst r rcases hp with hp | hp · have h₁ := congrArg Prod.fst hp have h₂ := congrArg Prod.snd hp exact Or.inl ⟨Or.inl h₁.symm,Or.inl h₂.symm⟩ · have h₁ := congrArg Prod.fst hp have h₂ := congrArg Prod.snd hp exact Or.inr ⟨Or.inl h₁.symm,Or.inl h₂.symm⟩ · rcases hout r hr (by simp [hrp,hn]) with hh | hh · exact Or.inl ⟨Or.inr hh.1,Or.inr hh.2⟩ · exact Or.inr ⟨Or.inr hh.1,Or.inr hh.2⟩ constructor · refine ⟨?_,hfresh.2.2.2.mono ?_,fun r hr => hsub r (List.mem_cons_of_mem _ hr),ho _ _ (Or.inl rfl)⟩ · simp only [Set.disjoint_insert_left,Set.mem_insert_iff,not_or,Set.disjoint_insert_right] tauto · intro x hx simp only [Set.mem_union,Set.mem_insert_iff] at hx ⊢ tauto · refine ⟨?_,hfresh.2.2.2.mono ?_,fun r hr => hsub r (List.mem_cons_of_mem _ hr),ho _ _ (Or.inr rfl)⟩ · simp only [Set.disjoint_insert_left,Set.mem_insert_iff,not_or,Set.disjoint_insert_right] tauto · intro x hx simp only [Set.mem_union,Set.mem_insert_iff] at hx ⊢ tauto lemma variance_node_bound (gs ps : List (Γ × Γ)) (f H : Set Γ → ℝ) (w : (Γ × Γ) → (Γ × Γ) → ℝ) (hf : ∀ S, 0 < f S) (hsig : HasSlotSignature f) (hgs : SlotsFresh gs ∅) (hw : ∀ p r, 0 < w p r) (hgood : ∀ p ∈ gs, ∀ r ∈ gs, p ≠ r → slotTotal gs f ∅ / (4*slotDefect gs f ∅ p r) ≤ w p r) (A B : Set Γ) (hnode : VarianceNode gs ps A B) (hne : ps ≠ []) : ∃ p qs, ps.Perm (p::qs) ∧ SlotsFresh (p::qs) A ∧ VarianceNode gs qs (insert p.1 A) (insert p.2 B) ∧ VarianceNode gs qs (insert p.2 A) (insert p.1 B) ∧ slotVariance (p::qs) f H A - slotVariance qs f H (insert p.1 A) - slotVariance qs f H (insert p.2 A) ≤ (1+8*(gs.length : ℝ))*restrictedEnergy (chainEdges gs) (chainConductance gs w f) H A B := by obtain ⟨p,hp,hsink⟩ := slot_scores_have_sink ps gs f hf hsig A ∅ (hnode.2.1.mono Set.subset_union_left) hgs hnode.2.2.1 hne let qs := ps.erase p have hperm : ps.Perm (p::qs) := List.perm_cons_erase hp have hnode' := hnode.perm hperm have hfr := hnode'.2.1 have hfrA : SlotsFresh (p::qs) A := hfr.mono Set.subset_union_left have hps : SlotsFresh qs (A ∪ Set.range (rootEmbedding p.1 p.2)) := hfrA.2.2.2.mono (by intro x hx rcases hx with hx | ⟨i,rfl⟩ · exact Or.inr (Or.inr hx) · cases i <;> simp [rootEmbedding]) let W := pairMultiplier qs (w p) have hW : ∀ x, 0 < W x := pairMultiplier_pos qs (w p) (hw p) have hws : ∀ r ∈ qs, W r.1 = W r.2 := by intro r hr dsimp only [W] rw [pairMultiplier_on hps _ r hr r.1 (Or.inl rfl), pairMultiplier_on hps _ r hr r.2 (Or.inr rfl)] have hWp : W p.1 = 1 := pairMultiplier_fresh hps _ _ (Or.inr ⟨false,rfl⟩) have hWd : W p.2 = 1 := pairMultiplier_fresh hps _ _ (Or.inr ⟨true,rfl⟩) have hsink' : ∀ x ∈ slotPunctures qs, slotTotal x.2 f (insert p.1 (insert p.2 A))/W x.1.1 ≤ 4*(slotTotal qs f (insert p.1 A)+slotTotal qs f (insert p.2 A)) := by intro x hx have hxq : x.1 ∈ qs := (slotPunctures_perm qs x hx).mem_iff.mpr List.mem_cons_self have hxp : p ≠ x.1 := hfr.pair_ne_of_mem hxq have hxps : x.1 ∈ ps := hperm.mem_iff.mpr (List.mem_cons_of_mem _ hxq) have hpG := hnode.2.2.1 p hp have hxG := hnode.2.2.1 x.1 hxps have hcpos := slotDefect_pos gs f hf ∅ hgs p x.1 hpG hxG hxp have hzpos := slotTotal_pos ps f hf A (hnode.2.1.mono Set.subset_union_left) have hs := hsink x.1 hxps hxp rw [slotDefect_perm hperm,slotDefect_puncture qs p A f hfrA x hx] at hs have hg := (div_le_iff₀ (mul_pos (by norm_num : (0:ℝ)<4) hcpos)).mp (hgood p hpG x.1 hxG hxp) have hgz := mul_le_mul_of_nonneg_left hg hzpos.le have hbound : slotTotal x.2 f (insert p.1 (insert p.2 A)) ≤ 4*slotTotal ps f A*w p x.1 := by apply (mul_le_mul_iff_of_pos_right hcpos).mp nlinarith change slotTotal x.2 f (insert p.1 (insert p.2 A))/pairMultiplier qs (w p) x.1.1 ≤ _ rw [pairMultiplier_on hps _ x.1 hxq x.1.1 (Or.inl rfl)] apply (div_le_iff₀ (hw p x.1)).mpr rw [slotTotal_perm hperm f,slotTotal_cons p qs f A hfrA.1 hfrA.2.1 hfrA.2.2.1] at hbound exact hbound have ht := transport_node_variance qs f H A p.1 p.2 W hf hsig hfrA.1 hfrA.2.1 hfrA.2.2.1 hps hW hws hWp hWd hsink' have he := variance_energy_identification gs qs A B p w f H hw hf hnode'.2.2.1 hnode'.1 hfr hnode'.2.2.2 have hqle : qs.length ≤ gs.length := by have hnodup := (hnode.2.1.nodup).erase p exact List.Subperm.length_le (List.subperm_of_subset hnodup (fun r hr => hnode'.2.2.1 r (List.mem_cons_of_mem _ hr))) have hqleR : (qs.length : ℝ) ≤ gs.length := by exact_mod_cast hqle have hepos : 0 ≤ restrictedEnergy (chainEdges gs) (chainConductance gs w f) H A B := by apply restrictedEnergy_nonneg intro ST _ exact le_min (mul_nonneg (chainMultiplier_pos gs w hw _).le (hf _).le) (mul_nonneg (chainMultiplier_pos gs w hw _).le (hf _).le) have hfinal := ht.trans ((mul_le_mul_of_nonneg_left he (by positivity : (0:ℝ) ≤ 1+8*(qs.length : ℝ))).trans (mul_le_mul_of_nonneg_right (by linarith : (1:ℝ)+8*(qs.length:ℝ) ≤ 1+8*(gs.length:ℝ)) hepos)) refine ⟨p,qs,hperm,hfrA,hnode'.children.1,hnode'.children.2,?_⟩ rw [slotVariance_split qs f H hf A p hfrA,slotTotal_cons p qs f A hfrA.1 hfrA.2.1 hfrA.2.2.1] linarith theorem transversal_variance_bound (gs : List (Γ × Γ)) (f H : Set Γ → ℝ) (w : (Γ × Γ) → (Γ × Γ) → ℝ) (hf : ∀ S, 0 < f S) (hsig : HasSlotSignature f) (hgs : SlotsFresh gs ∅) (hw : ∀ p r, 0 < w p r) (hgood : ∀ p ∈ gs, ∀ r ∈ gs, p ≠ r → slotTotal gs f ∅ / (4*slotDefect gs f ∅ p r) ≤ w p r) : slotVariance gs f H ∅ ≤ (gs.length : ℝ)*(1+8*(gs.length : ℝ))* restrictedEnergy (chainEdges gs) (chainConductance gs w f) H ∅ ∅ := by apply adaptive_variance_bound f H hf (chainEdges gs) (chainConductance gs w f) (fun ST _ => le_min (mul_nonneg (chainMultiplier_pos gs w hw _).le (hf _).le) (mul_nonneg (chainMultiplier_pos gs w hw _).le (hf _).le)) (1+8*(gs.length:ℝ)) (by positivity) (VarianceNode gs) (fun ps A B hnode hne => variance_node_bound gs ps f H w hf hsig hgs hw hgood A B hnode hne) exact ⟨by simp,by simpa using hgs,fun _ => id,fun r hr hn => False.elim (hn hr)⟩ end TransversalVariance section ChoiceEnumeration open scoped BigOperators Classical variable {Γ : Type*} [sectionInstance44 : Fintype Γ] [sectionInstance45 : DecidableEq Γ] def pairSupport (ps : List (Γ × Γ)) : Set Γ := {x | ∃ p ∈ ps, x = p.1 ∨ x = p.2} omit sectionInstance44 sectionInstance45 in @[simp] lemma pairSupport_nil [Fintype Γ] [DecidableEq Γ] : pairSupport ([] : List (Γ × Γ)) = ∅ := by ext; simp [pairSupport] omit sectionInstance44 sectionInstance45 in lemma pairSupport_cons [Fintype Γ] [DecidableEq Γ] (p : Γ × Γ) (ps : List (Γ × Γ)) : pairSupport (p::ps) = insert p.1 (insert p.2 (pairSupport ps)) := by ext x simp only [pairSupport,Set.mem_ofPred_eq,List.mem_cons,Set.mem_insert_iff] aesop noncomputable def choiceVertices (ps : List (Γ × Γ)) (A : Set Γ) : Finset (Set Γ) := match ps with | [] => {A} | p::ps => choiceVertices ps (insert p.1 A) ∪ choiceVertices ps (insert p.2 A) omit sectionInstance44 sectionInstance45 in lemma choiceVertices_fixed [Fintype Γ] [DecidableEq Γ] (ps : List (Γ × Γ)) (A S : Set Γ) (hS : S ∈ choiceVertices ps A) : A ⊆ S := by induction ps generalizing A with | nil => rw [choiceVertices,Finset.mem_singleton] at hS exact hS ▸ Set.Subset.rfl | cons p ps ih => rw [choiceVertices] at hS rcases Finset.mem_union.mp hS with hS | hS · exact (Set.subset_insert _ _).trans (ih _ hS) · exact (Set.subset_insert _ _).trans (ih _ hS) omit sectionInstance44 sectionInstance45 in lemma choiceVertices_excluded [Fintype Γ] [DecidableEq Γ] (ps : List (Γ × Γ)) (A B S : Set Γ) (hAB : Disjoint A B) (hps : ∀ p ∈ ps, p.1 ∉ B ∧ p.2 ∉ B) (hS : S ∈ choiceVertices ps A) : Disjoint B S := by induction ps generalizing A with | nil => rw [choiceVertices,Finset.mem_singleton] at hS exact hS ▸ hAB.symm | cons p ps ih => obtain ⟨ha,hb⟩ := hps p List.mem_cons_self have hrest := fun r hr => hps r (List.mem_cons_of_mem _ hr) rw [choiceVertices] at hS rcases Finset.mem_union.mp hS with hS | hS · exact ih _ (Set.disjoint_insert_left.mpr ⟨ha,hAB⟩) hrest hS · exact ih _ (Set.disjoint_insert_left.mpr ⟨hb,hAB⟩) hrest hS lemma choiceVertices_disjoint (ps : List (Γ × Γ)) (A : Set Γ) (p : Γ × Γ) (hps : SlotsFresh (p::ps) A) : Disjoint (choiceVertices ps (insert p.1 A)) (choiceVertices ps (insert p.2 A)) := by apply Finset.disjoint_left.mpr intro S h₁ h₂ have hp₁ : p.1 ∈ S := choiceVertices_fixed ps (insert p.1 A) S h₁ (Set.mem_insert _ _) have hp₂ : Disjoint {p.1} S := choiceVertices_excluded ps (insert p.2 A) {p.1} S (by simp only [Set.disjoint_singleton_right,Set.mem_insert_iff,not_or]; exact ⟨hps.1,hps.2.1⟩) (by intro r hr have hh := hps.2.2.2.elements_fresh r hr exact ⟨fun heq => hh.1 (Or.inl heq),fun heq => hh.2 (Or.inl heq)⟩) h₂ exact Set.disjoint_left.mp hp₂ rfl hp₁ lemma slotTotal_eq_choice_sum (ps : List (Γ × Γ)) (A : Set Γ) (f : Set Γ → ℝ) (hps : SlotsFresh ps A) : slotTotal ps f A = ∑ S ∈ choiceVertices ps A, f S := by induction ps generalizing A with | nil => simp [choiceVertices,slotTotal_nil] | cons p ps ih => rw [slotTotal_cons p ps f A hps.1 hps.2.1 hps.2.2.1,choiceVertices, Finset.sum_union (choiceVertices_disjoint ps A p hps)] congr 1 · exact ih _ (hps.2.2.2.mono (by intro x hx; simp only [Set.mem_insert_iff] at hx ⊢; tauto)) · exact ih _ (hps.2.2.2.mono (Set.subset_insert _ _)) lemma choiceVertices_card (ps : List (Γ × Γ)) (A : Set Γ) (hps : SlotsFresh ps A) : (choiceVertices ps A).card = 2^ps.length := by induction ps generalizing A with | nil => simp [choiceVertices] | cons p ps ih => rw [choiceVertices,Finset.card_union_of_disjoint (choiceVertices_disjoint ps A p hps), ih _ (hps.2.2.2.mono (by intro x hx; simp only [Set.mem_insert_iff] at hx ⊢; tauto)), ih _ (hps.2.2.2.mono (Set.subset_insert _ _)),List.length_cons,pow_succ] omega lemma mem_choiceVertices_iff (ps : List (Γ × Γ)) (A S : Set Γ) (hps : SlotsFresh ps A) : S ∈ choiceVertices ps A ↔ A ⊆ S ∧ S ⊆ A ∪ pairSupport ps ∧ PlainState ps S := by induction ps generalizing A with | nil => simp [choiceVertices,pairSupport_nil,PlainState,Set.Subset.antisymm_iff,and_comm] | cons p ps ih => have hf₁ : SlotsFresh ps (insert p.1 A) := hps.2.2.2.mono (by intro x hx; simp only [Set.mem_insert_iff] at hx ⊢; tauto) have hf₂ : SlotsFresh ps (insert p.2 A) := hps.2.2.2.mono (Set.subset_insert _ _) rw [choiceVertices,Finset.mem_union,ih _ hf₁,ih _ hf₂] have hnot₁ : p.1 ∉ pairSupport ps := by rintro ⟨r,hr,h⟩ have hh := hps.2.2.2.elements_fresh r hr rcases h with he | he · exact hh.1 (Or.inl he.symm) · exact hh.2 (Or.inl he.symm) have hnot₂ : p.2 ∉ pairSupport ps := by rintro ⟨r,hr,h⟩ have hh := hps.2.2.2.elements_fresh r hr rcases h with he | he · exact hh.1 (Or.inr (Or.inl he.symm)) · exact hh.2 (Or.inr (Or.inl he.symm)) constructor · rintro (⟨hfix,hsupp,hsing⟩ | ⟨hfix,hsupp,hsing⟩) · refine ⟨(Set.subset_insert _ _).trans hfix,?_,?_⟩ · intro x hx have hh := hsupp hx rw [pairSupport_cons] simp only [Set.mem_union,Set.mem_insert_iff] at hh ⊢ tauto · intro r hr rcases List.mem_cons.mp hr with rfl | hr · left refine ⟨hfix (Set.mem_insert _ _),?_⟩ intro hbad have hh := hsupp hbad rcases hh with hh | hh · rcases hh with hh | hh · exact hps.1 hh.symm · exact hps.2.2.1 hh · exact hnot₂ hh · exact hsing r hr · refine ⟨(Set.subset_insert _ _).trans hfix,?_,?_⟩ · intro x hx have hh := hsupp hx rw [pairSupport_cons] simp only [Set.mem_union,Set.mem_insert_iff] at hh ⊢ tauto · intro r hr rcases List.mem_cons.mp hr with rfl | hr · right refine ⟨hfix (Set.mem_insert _ _),?_⟩ intro hbad have hh := hsupp hbad rcases hh with hh | hh · rcases hh with hh | hh · exact hps.1 hh · exact hps.2.1 hh · exact hnot₁ hh · exact hsing r hr · rintro ⟨hfix,hsupp,hsing⟩ have hp := hsing p List.mem_cons_self have hrest : PlainState ps S := fun r hr => hsing r (List.mem_cons_of_mem _ hr) rcases hp with hp | hp · left refine ⟨Set.insert_subset hp.1 hfix,?_,hrest⟩ intro x hx have hh := hsupp hx rw [pairSupport_cons] at hh simp only [Set.mem_union,Set.mem_insert_iff] at hh ⊢ rcases hh with hh | rfl | rfl | hh · exact Or.inl (Or.inr hh) · exact Or.inl (Or.inl rfl) · exact False.elim (hp.2 hx) · exact Or.inr hh · right refine ⟨Set.insert_subset hp.1 hfix,?_,hrest⟩ intro x hx have hh := hsupp hx rw [pairSupport_cons] at hh simp only [Set.mem_union,Set.mem_insert_iff] at hh ⊢ rcases hh with hh | rfl | rfl | hh · exact Or.inl (Or.inr hh) · exact False.elim (hp.2 hx) · exact Or.inl (Or.inl rfl) · exact Or.inr hh lemma choiceVertices_plain (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hcover : pairSupport gs = Set.univ) : choiceVertices gs ∅ = Finset.univ.filter (PlainState gs) := by ext S rw [mem_choiceVertices_iff gs ∅ S hgs] simp [hcover] lemma slotTotal_eq_plain_sum (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hcover : pairSupport gs = Set.univ) (f : Set Γ → ℝ) : slotTotal gs f ∅ = ∑ S ∈ Finset.univ.filter (PlainState gs), f S := by rw [slotTotal_eq_choice_sum gs ∅ f hgs,choiceVertices_plain gs hgs hcover] lemma slotVariance_eq_plain_variance (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hcover : pairSupport gs = Set.univ) (f H : Set Γ → ℝ) : slotVariance gs f H ∅ = (∑ S ∈ Finset.univ.filter (PlainState gs), f S*(H S)^2) - (∑ S ∈ Finset.univ.filter (PlainState gs), f S*H S)^2 / (∑ S ∈ Finset.univ.filter (PlainState gs), f S) := by unfold slotVariance rw [slotTotal_eq_plain_sum gs hgs hcover,slotTotal_eq_plain_sum gs hgs hcover, slotTotal_eq_plain_sum gs hgs hcover] end ChoiceEnumeration section DefectEnumeration open scoped BigOperators Classical variable {Γ : Type*} [sectionInstance46 : Fintype Γ] [sectionInstance47 : DecidableEq Γ] omit sectionInstance46 sectionInstance47 in lemma pairSupport_perm [Fintype Γ] [DecidableEq Γ] {ps qs : List (Γ × Γ)} (hp : ps.Perm qs) : pairSupport ps = pairSupport qs := by ext x simp only [pairSupport,Set.mem_ofPred_eq,hp.mem_iff] lemma SlotsFresh.support_disjoint {ps : List (Γ × Γ)} {A : Set Γ} (h : SlotsFresh ps A) : Disjoint (pairSupport ps) A := by apply Set.disjoint_left.mpr rintro x ⟨p,hp,hx⟩ hxA rcases hx with rfl | rfl · exact (h.elements_fresh p hp).1 hxA · exact (h.elements_fresh p hp).2 hxA omit sectionInstance46 sectionInstance47 in lemma PlainState.perm [Fintype Γ] [DecidableEq Γ] {ps qs : List (Γ × Γ)} {S : Set Γ} (h : PlainState ps S) (hp : ps.Perm qs) : PlainState qs S := fun p hm => h p (hp.mem_iff.mpr hm) omit sectionInstance46 sectionInstance47 in lemma DefectState.perm [Fintype Γ] [DecidableEq Γ] {ps qs : List (Γ × Γ)} {p r : Γ × Γ} {S : Set Γ} (h : DefectState ps p r S) (hp : ps.Perm qs) : DefectState qs p r S := by exact ⟨hp.mem_iff.mp h.1,hp.mem_iff.mp h.2.1,h.2.2.1,h.2.2.2.1,h.2.2.2.2.1, fun t ht => h.2.2.2.2.2 t (hp.mem_iff.mpr ht)⟩ lemma choiceVertices_defect (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hcover : pairSupport gs = Set.univ) (p r : Γ × Γ) (hp : p ∈ gs) (hr : r ∈ gs) (hpr : p ≠ r) : choiceVertices ((gs.erase p).erase r) {r.1,r.2} = Finset.univ.filter (DefectState gs p r) := by let ps := (gs.erase p).erase r have hperm : gs.Perm (p::r::ps) := slots_perm_two hp hr hpr have hslots := (SlotsFresh.perm hperm ∅).mp hgs have htail : SlotsFresh ps {r.1,r.2} := hslots.2.2.2.2.2.2.mono (by intro x hx simp only [Set.mem_insert_iff,Set.mem_singleton_iff,Set.mem_empty_iff_false,or_false] at hx ⊢ tauto) have hno : p.1 ∉ pairSupport (r::ps) ∧ p.2 ∉ pairSupport (r::ps) := by exact ⟨fun hx => Set.disjoint_left.mp hslots.2.2.2.support_disjoint hx (Or.inl rfl), fun hx => Set.disjoint_left.mp hslots.2.2.2.support_disjoint hx (Or.inr (Or.inl rfl))⟩ have htailSupport : ({r.1,r.2} : Set Γ) ∪ pairSupport ps = pairSupport (r::ps) := by rw [pairSupport_cons] ext x simp only [Set.mem_union,Set.mem_insert_iff,Set.mem_singleton_iff] tauto have hcover' : pairSupport (p::r::ps) = Set.univ := (pairSupport_perm hperm).symm.trans hcover ext S rw [mem_choiceVertices_iff _ _ _ htail,Finset.mem_filter] simp only [Finset.mem_univ,true_and] constructor · rintro ⟨hfix,hsupp,hsing⟩ refine ⟨hp,hr,hpr,⟨?_,?_⟩,⟨hfix (Or.inl rfl),hfix (Or.inr rfl)⟩,?_⟩ · intro hx; exact hno.1 (htailSupport ▸ hsupp hx) · intro hx; exact hno.2 (htailSupport ▸ hsupp hx) · intro t ht htp htr have ht' : t ∈ p::r::ps := hperm.mem_iff.mp ht simp only [List.mem_cons] at ht' exact hsing t (ht'.resolve_left htp |>.resolve_left htr) · intro hdef refine ⟨?_,?_,?_⟩ · intro x hx rcases hx with rfl | hx · exact hdef.2.2.2.2.1.1 · exact hx ▸ hdef.2.2.2.2.1.2 · intro x hx have hh : x ∈ pairSupport (p::r::ps) := hcover' ▸ Set.mem_univ x rw [pairSupport_cons] at hh rcases hh with rfl | rfl | hh · exact False.elim (hdef.2.2.2.1.1 hx) · exact False.elim (hdef.2.2.2.1.2 hx) · exact htailSupport ▸ hh · intro t ht exact hdef.2.2.2.2.2 t (hperm.mem_iff.mpr (List.mem_cons_of_mem _ (List.mem_cons_of_mem _ ht))) (hslots.pair_ne_of_mem (List.mem_cons_of_mem _ ht)).symm (hslots.2.2.2.pair_ne_of_mem ht).symm lemma slotDefect_eq_defect_sum (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hcover : pairSupport gs = Set.univ) (f : Set Γ → ℝ) (p r : Γ × Γ) (hp : p ∈ gs) (hr : r ∈ gs) (hpr : p ≠ r) : slotDefect gs f ∅ p r = ∑ S ∈ Finset.univ.filter (DefectState gs p r), f S := by have hslots := (SlotsFresh.perm (slots_perm_two hp hr hpr) ∅).mp hgs have htail : SlotsFresh ((gs.erase p).erase r) {r.1,r.2} := hslots.2.2.2.2.2.2.mono (by intro x hx simp only [Set.mem_insert_iff,Set.mem_singleton_iff,Set.mem_empty_iff_false,or_false] at hx ⊢ tauto) unfold slotDefect simp only [insert_empty_eq] rw [slotTotal_eq_choice_sum _ _ f htail,choiceVertices_defect gs hgs hcover p r hp hr hpr] lemma choiceVertices_alternatives (ps : List (Γ × Γ)) (A : Set Γ) (p : Γ × Γ) (hps : SlotsFresh (p::ps) A) : slotTotal (p::ps) (fun _ => (1:ℝ)) A = 2^(ps.length+1) := by rw [slotTotal_eq_choice_sum _ _ _ hps] simp [choiceVertices_card _ _ hps] end DefectEnumeration section DefectTransport open scoped BigOperators Classical variable {Γ : Type*} [sectionInstance48 : Fintype Γ] [sectionInstance49 : DecidableEq Γ] def SamePair (p q : Γ × Γ) : Prop := q = p ∨ q = p.swap omit sectionInstance48 sectionInstance49 in lemma SamePair.full [Fintype Γ] [DecidableEq Γ] {p q : Γ × Γ} (h : SamePair p q) (S : Set Γ) : PairFull q S ↔ PairFull p S := by rcases h with rfl | rfl <;> simp [PairFull,and_comm] omit sectionInstance48 sectionInstance49 in lemma SamePair.empty [Fintype Γ] [DecidableEq Γ] {p q : Γ × Γ} (h : SamePair p q) (S : Set Γ) : PairEmpty q S ↔ PairEmpty p S := by rcases h with rfl | rfl <;> simp [PairEmpty,and_comm] omit sectionInstance48 sectionInstance49 in lemma SamePair.single [Fintype Γ] [DecidableEq Γ] {p q : Γ × Γ} (h : SamePair p q) (S : Set Γ) : PairSingle q S ↔ PairSingle p S := by rcases h with rfl | rfl <;> simp [PairSingle,or_comm] omit sectionInstance48 sectionInstance49 in lemma SamePair.set [Fintype Γ] [DecidableEq Γ] {p q : Γ × Γ} (h : SamePair p q) : ({q.1,q.2} : Set Γ) = {p.1,p.2} := by rcases h with rfl | rfl <;> simp [Set.pair_comm] omit sectionInstance48 sectionInstance49 in lemma SamePair.insert [Fintype Γ] [DecidableEq Γ] {p q : Γ × Γ} (h : SamePair p q) (A : Set Γ) : insert q.1 (insert q.2 A) = insert p.1 (insert p.2 A) := by rcases h with rfl | rfl <;> simp [Set.insert_comm] omit sectionInstance48 sectionInstance49 in lemma SamePair.fresh [Fintype Γ] [DecidableEq Γ] {p q : Γ × Γ} (h : SamePair p q) (ps : List (Γ × Γ)) (A : Set Γ) : SlotsFresh (q::ps) A ↔ SlotsFresh (p::ps) A := by rcases h with rfl | rfl · rfl · simp only [SlotsFresh,Prod.fst_swap,Prod.snd_swap,ne_eq] rw [Set.insert_comm] tauto lemma slot_energy_le_chain (gs ps : List (Γ × Γ)) (A : Set Γ) (p d : Γ) (W : Γ → ℝ) (w : (Γ × Γ) → (Γ × Γ) → ℝ) (f H : Set Γ → ℝ) (hw : ∀ p r, 0 < w p r) (hf : ∀ S, 0 < f S) (hv : ∀ S ∈ slotVertices ps A (rootEmbedding p d), ChainState gs S ∧ missingMultiplier ps (rootEmbedding p d) W S = chainMultiplier gs w S) : slotGraphEnergy ps f H A (rootEmbedding p d) W ≤ restrictedEnergy (chainEdges gs) (chainConductance gs w f) H ∅ ∅ := by unfold slotGraphEnergy restrictedEnergy simp only [EdgeRespects,Respects,Set.empty_subset,Set.empty_disjoint,true_and,ite_true] apply div_le_div_of_nonneg_right _ (by norm_num) have hE : slotGraphEdges ps A (rootEmbedding p d) ⊆ chainEdges gs := by intro ST hST obtain ⟨hp,ha⟩ := Finset.mem_filter.mp hST obtain ⟨hs,ht⟩ := Finset.mem_product.mp hp exact Finset.mem_filter.mpr ⟨Finset.mem_univ _,(hv _ hs).1,(hv _ ht).1,ha⟩ calc _ = ∑ ST ∈ slotGraphEdges ps A (rootEmbedding p d), chainConductance gs w f ST*(H ST.1-H ST.2)^2 := by apply Finset.sum_congr rfl intro ST hST obtain ⟨hs,ht⟩ := Finset.mem_product.mp (Finset.mem_filter.mp hST).1 simp only [slotEdgeEnergy,(hv _ hs).2,(hv _ ht).2,chainConductance] _ ≤ _ := by apply Finset.sum_le_sum_of_subset_of_nonneg hE intro ST _ _ exact mul_nonneg (le_min (mul_nonneg (chainMultiplier_pos gs w hw _).le (hf _).le) (mul_nonneg (chainMultiplier_pos gs w hw _).le (hf _).le)) (sq_nonneg _) lemma defect_vertex_identification (gs ps : List (Γ × Γ)) (p r u v : Γ × Γ) (hperm : gs.Perm (p::r::ps)) (hgs : SlotsFresh gs ∅) (hu : SamePair p u) (hv : SamePair r v) (w : (Γ × Γ) → (Γ × Γ) → ℝ) (S : Set Γ) (hS : S ∈ slotVertices ps {v.2} (rootEmbedding v.1 u.1)) : ChainState gs S ∧ missingMultiplier ps (rootEmbedding v.1 u.1) (pairMultiplier (r::ps) (w p)) S = chainMultiplier gs w S := by have hslots := (SlotsFresh.perm hperm ∅).mp hgs have horient : SlotsFresh (u::v::ps) ∅ := by apply (hu.fresh _ _).mpr change _ ∧ _ ∧ _ ∧ SlotsFresh (v::ps) (insert p.1 (insert p.2 ∅)) exact ⟨hslots.1,hslots.2.1,hslots.2.2.1,(hv.fresh _ _).mpr hslots.2.2.2⟩ have hfull : insert u.1 (insert u.2 (insert v.1 (insert v.2 (∅ : Set Γ)))) = insert v.1 (insert v.2 (insert u.1 (insert u.2 ∅))) := by ext x; simp only [Set.mem_insert_iff]; tauto have htail := horient.2.2.2.2.2.2 have hbase : SlotsFresh ps ({v.2} ∪ Set.range (rootEmbedding v.1 u.1)) := htail.mono (by intro x hx rcases hx with hx | ⟨i,rfl⟩ · simp only [Set.mem_singleton_iff] at hx; subst x; simp · cases i <;> simp [rootEmbedding]) have hne : v.1 ≠ u.1 := by intro he; exact horient.2.2.2.2.1 (Or.inl he) have hvu : v.2 ≠ u.1 := by intro he; exact horient.2.2.2.2.2.1 (Or.inl he) have heA : ∀ j, rootEmbedding v.1 u.1 j ∉ ({v.2} : Set Γ) := by intro j; cases j · exact horient.2.2.2.1 · exact hvu.symm have hinc : v.2 ∈ S := slotVertices_fixed ps {v.2} _ S hS rfl have heB : ∀ j, rootEmbedding v.1 u.1 j ∉ ({u.2} : Set Γ) := by intro j; cases j · exact fun he => horient.2.2.2.2.1 (Or.inr (Or.inl he)) · exact horient.1 have hexc : u.2 ∉ S := by have hh := slotVertices_excluded ps {v.2} {u.2} (rootEmbedding v.1 u.1) (by simpa only [Set.disjoint_singleton] using (show v.2 ≠ u.2 from fun he => horient.2.2.2.2.2.1 (Or.inr (Or.inl he)))) heB (fun t ht => let hh := htail.elements_fresh t ht ⟨fun he => hh.1 (Or.inr (Or.inr (Or.inr (Or.inl he)))), fun he => hh.2 (Or.inr (Or.inr (Or.inr (Or.inl he))))⟩) S hS exact fun hx => Set.disjoint_left.mp hh rfl hx have hmem (t : Γ × Γ) (ht : t ∈ gs) (hp : t ≠ p) (hr : t ≠ r) : t ∈ ps := ((List.mem_cons.mp (hperm.mem_iff.mp ht)).resolve_left hp |> List.mem_cons.mp).resolve_left hr have hp : p ∈ gs := hperm.mem_iff.mpr List.mem_cons_self have hr : r ∈ gs := hperm.mem_iff.mpr (List.mem_cons_of_mem _ List.mem_cons_self) have hpr : p ≠ r := hslots.pair_ne_of_mem List.mem_cons_self have hcl := slotVertices_classify ps {v.2} _ (rootEmbedding_injective _ _ hne) heA hbase S hS rcases hcl with ⟨j,hj,hrest⟩ | ⟨t,ht,he,hfull,hrest⟩ · cases j · have hdef : DefectState gs p r S := by refine ⟨hp,hr,hpr,(hu.empty S).mp ⟨?_,hexc⟩,(hv.full S).mp ⟨?_,hinc⟩,?_⟩ · exact fun hh => Bool.noConfusion ((hj true).mp hh) · exact (hj false).mpr rfl · intro t ht htp htr; exact hrest t (hmem t ht htp htr) refine ⟨Or.inr ⟨p,r,hdef⟩,?_⟩ rw [chainMultiplier_defect gs w S hdef,missingMultiplier_old ps _ _ S false hj hrest] apply pairMultiplier_on hslots.2.2.2 _ r List.mem_cons_self v.1 rcases hv with rfl | rfl <;> simp · have hplain : PlainState gs S := by intro t ht by_cases ht₁ : t = p · subst t; apply (hu.single S).mp; exact Or.inl ⟨(hj true).mpr rfl,hexc⟩ by_cases ht₂ : t = r · subst t; apply (hv.single S).mp exact Or.inr ⟨hinc,fun hh => Bool.noConfusion ((hj false).mp hh)⟩ exact hrest t (hmem t ht ht₁ ht₂) refine ⟨Or.inl hplain,?_⟩ rw [chainMultiplier_plain gs w S hplain,missingMultiplier_old ps _ _ S true hj hrest] apply pairMultiplier_fresh hslots.2.2.2 rcases hu with rfl | rfl <;> simp [rootEmbedding] · have hdef : DefectState gs p t S := by refine ⟨hp,hperm.mem_iff.mpr (List.mem_cons_of_mem _ (List.mem_cons_of_mem _ ht)), hslots.pair_ne_of_mem (List.mem_cons_of_mem _ ht),(hu.empty S).mp ⟨he true,hexc⟩,hfull,?_⟩ intro z hz hzp hzt by_cases hzr : z = r · subst z; exact (hv.single S).mp (Or.inr ⟨hinc,he false⟩) · exact hrest z (hmem z hz hzp hzr) hzt refine ⟨Or.inr ⟨p,t,hdef⟩,?_⟩ rw [chainMultiplier_defect gs w S hdef, missingMultiplier_new ps htail.nodup _ _ S t ht he hfull hrest] exact pairMultiplier_on hslots.2.2.2 _ t (List.mem_cons_of_mem _ ht) t.1 (Or.inl rfl) lemma SamePair.fresh_two {p r u v : Γ × Γ} (hu : SamePair p u) (hv : SamePair r v) (ps : List (Γ × Γ)) (A : Set Γ) (h : SlotsFresh (p::r::ps) A) : SlotsFresh (u::v::ps) A := by apply (hu.fresh _ _).mpr exact ⟨h.1,h.2.1,h.2.2.1,(hv.fresh _ _).mpr h.2.2.2⟩ lemma slotDefect_rest (gs ps : List (Γ × Γ)) (p r : Γ × Γ) (hperm : gs.Perm (p::r::ps)) (f : Set Γ → ℝ) : slotDefect gs f ∅ p r = slotTotal ps f {r.1,r.2} := by rw [slotDefect_perm hperm] simp [slotDefect] lemma defect_puncture_le (gs ps : List (Γ × Γ)) (p r u v : Γ × Γ) (hperm : gs.Perm (p::r::ps)) (hgs : SlotsFresh gs ∅) (hu : SamePair p u) (hv : SamePair r v) (f : Set Γ → ℝ) (hf : ∀ S, 0 < f S) (x : (Γ × Γ) × List (Γ × Γ)) (hx : x ∈ slotPunctures ps) : slotTotal x.2 f (insert v.1 (insert u.1 {v.2})) ≤ slotDefect gs f ∅ x.1 r := by have hxp := slotPunctures_perm ps x hx have hxmem : x.1 ∈ ps := hxp.mem_iff.mpr List.mem_cons_self have hslots := (SlotsFresh.perm hperm ∅).mp hgs have hpt := hslots.pair_ne_of_mem (List.mem_cons_of_mem _ hxmem) have hrt := hslots.2.2.2.pair_ne_of_mem hxmem have hpr := hslots.pair_ne_of_mem List.mem_cons_self have heq : insert v.1 (insert u.1 ({v.2} : Set Γ)) = insert u.1 {r.1,r.2} := by rw [Set.insert_comm v.1 u.1,hv.set] rw [heq,slotDefect_perm (hperm.trans ((hxp.cons r).cons p))] simp only [slotDefect] simp [hpt,hrt,hpr,insert_empty_eq] have hp₁ : p.1 ∉ ({r.1,r.2} : Set Γ) := by rintro (he | he) · exact hslots.2.2.2.2.1 (Or.inl he.symm) · exact hslots.2.2.2.2.2.1 (Or.inl he.symm) have hp₂ : p.2 ∉ ({r.1,r.2} : Set Γ) := by rintro (he | he) · exact hslots.2.2.2.2.1 (Or.inr (Or.inl he.symm)) · exact hslots.2.2.2.2.2.1 (Or.inr (Or.inl he.symm)) rw [slotTotal_cons p x.2 f {r.1,r.2} hslots.1 hp₁ hp₂] rcases hu with rfl | rfl · exact le_add_of_nonneg_right (slotTotal_nonneg _ f (fun S => (hf S).le) _) · exact le_add_of_nonneg_left (slotTotal_nonneg _ f (fun S => (hf S).le) _) theorem defect_conditional_transport (gs ps : List (Γ × Γ)) (p r u v : Γ × Γ) (hperm : gs.Perm (p::r::ps)) (hgs : SlotsFresh gs ∅) (hu : SamePair p u) (hv : SamePair r v) (f H : Set Γ → ℝ) (hf : ∀ S, 0 < f S) (hsig : HasSlotSignature f) (w : (Γ × Γ) → (Γ × Γ) → ℝ) (hw : ∀ p r, 0 < w p r) (hgood : ∀ p ∈ gs, ∀ r ∈ gs, p ≠ r → slotTotal gs f ∅/(4*slotDefect gs f ∅ p r) ≤ w p r) : let z := slotTotal gs f ∅ let sp := slotDefect gs f ∅ p r let sd := slotTotal ps f {u.1,v.2} sd*(slotDefect gs (fun S => f S*H S) ∅ p r/sp - slotTotal ps (fun S => f S*H S) {u.1,v.2}/sd)^2 ≤ (4*sd/z+1+8*(ps.length:ℝ))* restrictedEnergy (chainEdges gs) (chainConductance gs w f) H ∅ ∅ := by let z := slotTotal gs f ∅ let sp := slotDefect gs f ∅ p r let sd := slotTotal ps f {u.1,v.2} let W := pairMultiplier (r::ps) (w p) let D := restrictedEnergy (chainEdges gs) (chainConductance gs w f) H ∅ ∅ have hslots := (SlotsFresh.perm hperm ∅).mp hgs have horient := hu.fresh_two hv ps ∅ hslots have hp : p ∈ gs := hperm.mem_iff.mpr List.mem_cons_self have hr : r ∈ gs := hperm.mem_iff.mpr (List.mem_cons_of_mem _ List.mem_cons_self) have hpr := hslots.pair_ne_of_mem List.mem_cons_self have hz : 0 < z := slotTotal_pos gs f hf ∅ hgs have hsp : 0 < sp := slotDefect_pos gs f hf ∅ hgs p r hp hr hpr have hsd : 0 < sd := slotTotal_pos ps f hf _ (horient.2.2.2.2.2.2.mono (by intro x hx simp only [Set.mem_insert_iff,Set.mem_singleton_iff] at hx ⊢ rcases hx with rfl | rfl <;> simp)) have hbase : SlotsFresh ps ({v.2} ∪ Set.range (rootEmbedding v.1 u.1)) := horient.2.2.2.2.2.2.mono (by intro x hx rcases hx with hx | ⟨i,rfl⟩ · simp only [Set.mem_singleton_iff] at hx; subst x; simp · cases i <;> simp [rootEmbedding]) have hne : v.1 ≠ u.1 := fun he => horient.2.2.2.2.1 (Or.inl he) have hpA : v.1 ∉ ({v.2} : Set Γ) := horient.2.2.2.1 have hdA : u.1 ∉ ({v.2} : Set Γ) := fun he => horient.2.2.2.2.2.1 (Or.inl he.symm) have hW : ∀ x, 0 < W x := pairMultiplier_pos _ _ (hw p) have hws : ∀ t ∈ ps, W t.1 = W t.2 := by intro t ht dsimp [W] rw [pairMultiplier_on hslots.2.2.2 _ t (List.mem_cons_of_mem _ ht) t.1 (Or.inl rfl), pairMultiplier_on hslots.2.2.2 _ t (List.mem_cons_of_mem _ ht) t.2 (Or.inr rfl)] have hWp : W v.1 = w p r := by apply pairMultiplier_on hslots.2.2.2 _ r List.mem_cons_self v.1 rcases hv with rfl | rfl <;> simp have hWd : W u.1 = 1 := by apply pairMultiplier_fresh hslots.2.2.2 rcases hu with rfl | rfl <;> simp have heqsp (g : Set Γ → ℝ) : slotTotal ps g (insert v.1 {v.2}) = slotDefect gs g ∅ p r := by rw [hv.set,slotDefect_rest gs ps p r hperm g] have hgoodpr : z ≤ 4*sp*w p r := by have hh := (div_le_iff₀ (by positivity : 0 < 4*sp)).mp (hgood p hp r hr hpr) dsimp [z,sp] at *; nlinarith have hfirst : 1/(sp*w p r) ≤ 4/z := by apply (div_le_div_iff₀ (mul_pos hsp (hw p r)) hz).mpr nlinarith have hsink : ∀ x ∈ slotPunctures ps, slotTotal x.2 f (insert v.1 (insert u.1 {v.2}))/W x.1.1 ≤ 4*sp := by intro x hx have hxmem : x.1 ∈ ps := (slotPunctures_perm ps x hx).mem_iff.mpr List.mem_cons_self have hxg : x.1 ∈ gs := hperm.mem_iff.mpr (List.mem_cons_of_mem _ (List.mem_cons_of_mem _ hxmem)) have hpt := hslots.pair_ne_of_mem (List.mem_cons_of_mem _ hxmem) have hrt := hslots.2.2.2.pair_ne_of_mem hxmem have hcx := slotDefect_pos gs f hf ∅ hgs p x.1 hp hxg hpt have htriple := slotDefect_triple_bound gs f hf hsig ∅ hgs p x.1 r hp hxg hr hpt hrt.symm hpr have hvle := defect_puncture_le gs ps p r u v hperm hgs hu hv f hf x hx have hg := (div_le_iff₀ (by positivity : 0 < 4*slotDefect gs f ∅ p x.1)).mp (hgood p hp x.1 hxg hpt) have hg' := mul_le_mul_of_nonneg_left hg hsp.le have hv' := mul_le_mul_of_nonneg_left hvle hcx.le have hb : slotTotal x.2 f (insert v.1 (insert u.1 {v.2})) ≤ 4*sp*w p x.1 := by apply (mul_le_mul_iff_of_pos_right hcx).mp dsimp [z,sp] at * nlinarith dsimp [W] rw [pairMultiplier_on hslots.2.2.2 _ x.1 (List.mem_cons_of_mem _ hxmem) x.1.1 (Or.inl rfl)] exact (div_le_iff₀ (hw p x.1)).mpr hb have hsum := list_sum_map_le_const (slotPunctures ps) (fun x => slotTotal x.2 f (insert v.1 (insert u.1 {v.2}))/W x.1.1) (4*sp) hsink rw [slotPunctures_length] at hsum have hcoef : sd*rootCoefficient ps f {v.2} v.1 u.1 W ≤ 4*sd/z+1+8*(ps.length:ℝ) := by unfold rootCoefficient rw [heqsp f,hWp,hWd] dsimp only rw [mul_one] change sd*(1/(sp*w p r)+1/sd+2/(sp*sd)*_) ≤ _ have h₁ := mul_le_mul_of_nonneg_left hfirst hsd.le have h₂ := mul_le_mul_of_nonneg_left hsum (show 0 ≤ 2/sp by positivity) have heq (a b : ℝ) : sd*(a+1/sd+2/(sp*sd)*b) = sd*a+1+(2/sp)*b := by field_simp rw [heq] have heq' : 2/sp*((ps.length:ℝ)*(4*sp)) = 8*(ps.length:ℝ) := by field_simp ; ring rw [heq'] at h₂ calc _ ≤ sd*(4/z)+1+8*(ps.length:ℝ) := by linarith only [h₁,h₂] _ = _ := by ring have he := slot_energy_le_chain gs ps {v.2} v.1 u.1 W w f H hw hf (defect_vertex_identification gs ps p r u v hperm hgs hu hv w) have ht := transport_graph_bound ps f H {v.2} v.1 u.1 W hf hsig hne hpA hdA hbase hW hws have hcp := rootCoefficient_pos ps f hf {v.2} v.1 u.1 W hbase hW have hD : 0 ≤ D := restrictedEnergy_nonneg _ _ _ _ _ (by intro ST _ exact le_min (mul_nonneg (chainMultiplier_pos gs w hw _).le (hf _).le) (mul_nonneg (chainMultiplier_pos gs w hw _).le (hf _).le)) have htnew := mul_le_mul_of_nonneg_left ht hsd.le rw [← mul_assoc] at htnew have hb := htnew.trans ((mul_le_mul_of_nonneg_left he (mul_nonneg hsd.le hcp.le)).trans (mul_le_mul_of_nonneg_right hcoef hD)) simpa only [heqsp f,heqsp (fun S => f S*H S),← mul_assoc] using hb end DefectTransport section DefectMeans open scoped BigOperators Classical variable {Γ : Type*} [sectionInstance50 : Fintype Γ] [sectionInstance51 : DecidableEq Γ] def orientPair (p : Γ × Γ) (b : Bool) : Γ × Γ := if b then p.swap else p omit sectionInstance50 sectionInstance51 in lemma orientPair_same [Fintype Γ] [DecidableEq Γ] (p : Γ × Γ) (b : Bool) : SamePair p (orientPair p b) := by cases b <;> simp [orientPair,SamePair] lemma slotTotal_four (gs ps : List (Γ × Γ)) (p r : Γ × Γ) (hperm : gs.Perm (p::r::ps)) (hgs : SlotsFresh gs ∅) (f : Set Γ → ℝ) : ∑ o : Bool × Bool, slotTotal ps f {(orientPair p o.1).1,(orientPair r o.2).2} = slotTotal gs f ∅ := by have hslots := (SlotsFresh.perm hperm ∅).mp hgs have hr₁ : r.1 ∉ (insert p.1 (∅ : Set Γ)) := fun hx => hslots.2.2.2.2.1 (by simp only [Set.mem_insert_iff] at hx ⊢; tauto) have hr₂ : r.2 ∉ (insert p.1 (∅ : Set Γ)) := fun hx => hslots.2.2.2.2.2.1 (by simp only [Set.mem_insert_iff] at hx ⊢; tauto) have hr₃ : r.1 ∉ (insert p.2 (∅ : Set Γ)) := fun hx => hslots.2.2.2.2.1 (Or.inr hx) have hr₄ : r.2 ∉ (insert p.2 (∅ : Set Γ)) := fun hx => hslots.2.2.2.2.2.1 (Or.inr hx) rw [slotTotal_perm hperm f,slotTotal_cons p (r::ps) f ∅ hslots.1 hslots.2.1 hslots.2.2.1, slotTotal_cons r ps f _ hslots.2.2.2.1 hr₁ hr₂, slotTotal_cons r ps f _ hslots.2.2.2.1 hr₃ hr₄] simp only [Fintype.sum_prod_type,Fintype.sum_bool,orientPair,Bool.false_eq_true, ite_false,ite_true,Prod.fst_swap,Prod.snd_swap,insert_empty_eq] rw [Set.pair_comm r.1 p.1,Set.pair_comm r.2 p.1,Set.pair_comm r.1 p.2,Set.pair_comm r.2 p.2] ring lemma weighted_square_mean {J : Type*} [Fintype J] (w x : J → ℝ) (hw : ∀ j, 0 < w j) : (∑ j, w j*x j)^2/(∑ j, w j) ≤ ∑ j, w j*(x j)^2 := by have h := Finset.sq_sum_div_le_sum_sq_div Finset.univ (fun j => w j*x j) (fun j _ => hw j) have heq : (∑ j, (w j*x j)^2/w j) = ∑ j, w j*(x j)^2 := by apply Finset.sum_congr rfl intro j _ field_simp [ne_of_gt (hw j)] rw [heq] at h exact h theorem defect_mean_bound (gs : List (Γ × Γ)) (p r : Γ × Γ) (hgs : SlotsFresh gs ∅) (hp : p ∈ gs) (hr : r ∈ gs) (hpr : p ≠ r) (f H : Set Γ → ℝ) (hf : ∀ S, 0 < f S) (hsig : HasSlotSignature f) (w : (Γ × Γ) → (Γ × Γ) → ℝ) (hw : ∀ p r, 0 < w p r) (hgood : ∀ p ∈ gs, ∀ r ∈ gs, p ≠ r → slotTotal gs f ∅/(4*slotDefect gs f ∅ p r) ≤ w p r) : slotTotal gs f ∅ * (slotDefect gs (fun S => f S*H S) ∅ p r/slotDefect gs f ∅ p r - slotTotal gs (fun S => f S*H S) ∅/slotTotal gs f ∅)^2 ≤ (8+32*(gs.length:ℝ))*restrictedEnergy (chainEdges gs) (chainConductance gs w f) H ∅ ∅ := by let ps := (gs.erase p).erase r have hperm : gs.Perm (p::r::ps) := slots_perm_two hp hr hpr let z := slotTotal gs f ∅ let m := slotDefect gs (fun S => f S*H S) ∅ p r/slotDefect gs f ∅ p r let s : Bool × Bool → ℝ := fun o => slotTotal ps f {(orientPair p o.1).1,(orientPair r o.2).2} let a : Bool × Bool → ℝ := fun o => slotTotal ps (fun S => f S*H S) {(orientPair p o.1).1,(orientPair r o.2).2} let D := restrictedEnergy (chainEdges gs) (chainConductance gs w f) H ∅ ∅ have hz : 0 < z := slotTotal_pos gs f hf ∅ hgs have hs : ∀ o, 0 < s o := by intro o have hh := (orientPair_same p o.1).fresh_two (orientPair_same r o.2) ps ∅ ((SlotsFresh.perm hperm ∅).mp hgs) apply slotTotal_pos ps f hf _ (hh.2.2.2.2.2.2.mono _) intro x hx simp only [Set.mem_insert_iff,Set.mem_singleton_iff] at hx ⊢ rcases hx with rfl | rfl <;> simp have hsum : ∑ o, s o = z := slotTotal_four gs ps p r hperm hgs f have hsumA : ∑ o, a o = slotTotal gs (fun S => f S*H S) ∅ := slotTotal_four gs ps p r hperm hgs _ have ha (o : Bool × Bool) : s o*(m-a o/s o) = s o*m-a o := by field_simp [ne_of_gt (hs o)] have hmean := weighted_square_mean s (fun o => m-a o/s o) hs simp_rw [ha] at hmean rw [Finset.sum_sub_distrib,← Finset.sum_mul,hsum,hsumA] at hmean have heq : (z*m-slotTotal gs (fun S => f S*H S) ∅)^2/z = z*(m-slotTotal gs (fun S => f S*H S) ∅/z)^2 := by field_simp rw [heq] at hmean have hc (o : Bool × Bool) : s o*(m-a o/s o)^2 ≤ (4*s o/z+1+8*(ps.length:ℝ))*D := defect_conditional_transport gs ps p r (orientPair p o.1) (orientPair r o.2) hperm hgs (orientPair_same p o.1) (orientPair_same r o.2) f H hf hsig w hw hgood have hsumc := Finset.sum_le_sum (fun o (_ : o ∈ (Finset.univ : Finset (Bool × Bool))) => hc o) have hsumcoef : (∑ o : Bool × Bool, (4*s o/z+1+8*(ps.length:ℝ))*D) = (8+32*(ps.length:ℝ))*D := by rw [← Finset.sum_mul] congr 1 simp only [Finset.sum_add_distrib,← Finset.sum_div,← Finset.mul_sum,hsum] simp [ne_of_gt hz] ; ring rw [hsumcoef] at hsumc have hD : 0 ≤ D := restrictedEnergy_nonneg _ _ _ _ _ (by intro ST _ exact le_min (mul_nonneg (chainMultiplier_pos gs w hw _).le (hf _).le) (mul_nonneg (chainMultiplier_pos gs w hw _).le (hf _).le)) have hlen : (ps.length:ℝ) ≤ gs.length := by have hh := hperm.length_eq simp only [List.length_cons] at hh exact_mod_cast (show ps.length ≤ gs.length by omega) exact (hmean.trans hsumc).trans (mul_le_mul_of_nonneg_right (by linarith) hD) end DefectMeans section Observable open scoped BigOperators Classical variable {Γ : Type*} [sectionInstance52 : Fintype Γ] [DecidableEq Γ] noncomputable def chainStates (gs : List (Γ × Γ)) : Finset (Set Γ) := Finset.univ.filter (ChainState gs) noncomputable def defectTypes (gs : List (Γ × Γ)) : Finset ((Γ × Γ) × (Γ × Γ)) := gs.toFinset.offDiag noncomputable def chainWeight (gs : List (Γ × Γ)) (w : (Γ × Γ) → (Γ × Γ) → ℝ) (f : Set Γ → ℝ) (S : Set Γ) : ℝ := chainMultiplier gs w S * f S noncomputable def chainTotal (gs : List (Γ × Γ)) (w : (Γ × Γ) → (Γ × Γ) → ℝ) (f : Set Γ → ℝ) : ℝ := ∑ S ∈ chainStates gs, chainWeight gs w f S noncomputable def plainMean (gs : List (Γ × Γ)) (f H : Set Γ → ℝ) : ℝ := slotTotal gs (fun S => f S*H S) ∅/slotTotal gs f ∅ noncomputable def defectMean (gs : List (Γ × Γ)) (f H : Set Γ → ℝ) (p r : Γ × Γ) : ℝ := slotDefect gs (fun S => f S*H S) ∅ p r/slotDefect gs f ∅ p r noncomputable def observableProjection (gs : List (Γ × Γ)) (f H : Set Γ → ℝ) (S : Set Γ) : ℝ := if h : ∃ p r, DefectState gs p r S then defectMean gs f H h.choose h.choose_spec.choose else H S lemma observableProjection_plain (gs : List (Γ × Γ)) (f H : Set Γ → ℝ) (S : Set Γ) (h : PlainState gs S) : observableProjection gs f H S = H S := by unfold observableProjection rw [dite_eq_right] rintro ⟨p,r,hpr⟩ exact hpr.not_plain h lemma observableProjection_defect (gs : List (Γ × Γ)) (f H : Set Γ → ℝ) (S : Set Γ) {p r : Γ × Γ} (h : DefectState gs p r S) : observableProjection gs f H S = defectMean gs f H p r := by have he : ∃ p r, DefectState gs p r S := ⟨p,r,h⟩ unfold observableProjection rw [dite_eq_left he] have hh := he.choose_spec.choose_spec.unique h exact congrArg₂ (defectMean gs f H) hh.1 hh.2 omit sectionInstance52 in lemma mem_defectTypes [Fintype Γ] (gs : List (Γ × Γ)) (pr : (Γ × Γ) × (Γ × Γ)) : pr ∈ defectTypes gs ↔ pr.1 ∈ gs ∧ pr.2 ∈ gs ∧ pr.1 ≠ pr.2 := by simp [defectTypes,Finset.mem_offDiag] lemma chain_sum_decomposition (gs : List (Γ × Γ)) (w : (Γ × Γ) → (Γ × Γ) → ℝ) (g : Set Γ → ℝ) : (∑ S ∈ chainStates gs, chainMultiplier gs w S*g S) = (∑ S ∈ Finset.univ.filter (PlainState gs),g S) + ∑ pr ∈ defectTypes gs, w pr.1 pr.2 * ∑ S ∈ Finset.univ.filter (DefectState gs pr.1 pr.2),g S := by simp only [chainStates,Finset.sum_filter,Finset.mul_sum] rw [Finset.sum_comm,← Finset.sum_add_distrib] apply Finset.sum_congr rfl intro S _ by_cases hp : PlainState gs S · have hd : ∀ p r, ¬ DefectState gs p r S := fun p r hh => hh.not_plain hp simp [hp,ChainState,chainMultiplier_plain gs w S hp,hd] · by_cases hd : ∃ p r, DefectState gs p r S · obtain ⟨p,r,hpr⟩ := hd have hmem : (p,r) ∈ defectTypes gs := (mem_defectTypes gs _).mpr ⟨hpr.1,hpr.2.1,hpr.2.2.1⟩ have hu : ∀ pr ∈ defectTypes gs, pr ≠ (p,r) → ¬ DefectState gs pr.1 pr.2 S := by intro pr _ hn hh have he := hh.unique hpr exact hn (Prod.ext he.1 he.2) rw [ite_eq_left (show ChainState gs S from Or.inr ⟨p,r,hpr⟩),ite_eq_right hp,zero_add, Finset.sum_eq_single (p,r)] · simp [hpr,chainMultiplier_defect gs w S hpr] · intro pr hm hn simp [hu pr hm hn] · exact fun hn => False.elim (hn hmem) · have hd' : ∀ p r, ¬ DefectState gs p r S := fun p r hh => hd ⟨p,r,hh⟩ simp [ChainState,hp,hd'] lemma chainTotal_eq (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hcover : pairSupport gs = Set.univ) (w : (Γ × Γ) → (Γ × Γ) → ℝ) (f : Set Γ → ℝ) : chainTotal gs w f = slotTotal gs f ∅ + ∑ pr ∈ defectTypes gs, w pr.1 pr.2*slotDefect gs f ∅ pr.1 pr.2 := by unfold chainTotal chainWeight rw [chain_sum_decomposition,← slotTotal_eq_plain_sum gs hgs hcover f] congr 1 apply Finset.sum_congr rfl intro pr hm obtain ⟨hp,hr,hpr⟩ := (mem_defectTypes gs pr).mp hm rw [slotDefect_eq_defect_sum gs hgs hcover f pr.1 pr.2 hp hr hpr] lemma chainTotal_ge_plain (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hcover : pairSupport gs = Set.univ) (w : (Γ × Γ) → (Γ × Γ) → ℝ) (f : Set Γ → ℝ) (hf : ∀ S, 0 < f S) (hw : ∀ p r, 0 < w p r) : slotTotal gs f ∅ ≤ chainTotal gs w f := by rw [chainTotal_eq gs hgs hcover w f] apply le_add_of_nonneg_right apply Finset.sum_nonneg intro pr hm obtain ⟨hp,hr,hpr⟩ := (mem_defectTypes gs pr).mp hm exact mul_nonneg (hw _ _).le (slotDefect_pos gs f hf ∅ hgs pr.1 pr.2 hp hr hpr).le lemma chainTotal_pos (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hcover : pairSupport gs = Set.univ) (w : (Γ × Γ) → (Γ × Γ) → ℝ) (f : Set Γ → ℝ) (hf : ∀ S, 0 < f S) (hw : ∀ p r, 0 < w p r) : 0 < chainTotal gs w f := (slotTotal_pos gs f hf ∅ hgs).trans_le (chainTotal_ge_plain gs hgs hcover w f hf hw) omit sectionInstance52 in lemma defectTypes_card_le [Fintype Γ] (gs : List (Γ × Γ)) : (defectTypes gs).card ≤ gs.length*gs.length := by calc _ ≤ gs.toFinset.card*gs.toFinset.card := by simp [defectTypes,Finset.offDiag_card] _ ≤ _ := Nat.mul_le_mul (List.toFinset_card_le _) (List.toFinset_card_le _) lemma chainTotal_le (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hne : gs ≠ []) (hcover : pairSupport gs = Set.univ) (w : (Γ × Γ) → (Γ × Γ) → ℝ) (f : Set Γ → ℝ) (hf : ∀ S, 0 < f S) (hupper : ∀ p ∈ gs, ∀ r ∈ gs, p ≠ r → w p r ≤ 4*slotTotal gs f ∅/slotDefect gs f ∅ p r) : chainTotal gs w f ≤ 5*(gs.length:ℝ)^2*slotTotal gs f ∅ := by rw [chainTotal_eq gs hgs hcover w f] have hz := slotTotal_pos gs f hf ∅ hgs have hc : (∑ pr ∈ defectTypes gs, w pr.1 pr.2*slotDefect gs f ∅ pr.1 pr.2) ≤ (defectTypes gs).card*(4*slotTotal gs f ∅) := by calc _ ≤ ∑ _pr ∈ defectTypes gs, 4*slotTotal gs f ∅ := by apply Finset.sum_le_sum intro pr hm obtain ⟨hp,hr,hpr⟩ := (mem_defectTypes gs pr).mp hm exact (le_div_iff₀ (slotDefect_pos gs f hf ∅ hgs pr.1 pr.2 hp hr hpr)).mp (hupper pr.1 hp pr.2 hr hpr) _ = _ := by simp have hcard : ((defectTypes gs).card:ℝ) ≤ (gs.length:ℝ)^2 := by exact_mod_cast (show (defectTypes gs).card ≤ gs.length^2 by simpa [pow_two] using defectTypes_card_le gs) have hn : 1 ≤ (gs.length:ℝ) := by exact_mod_cast List.length_pos_iff.mpr hne have hn2 : 1 ≤ (gs.length:ℝ)^2 := by nlinarith nlinarith [mul_le_mul_of_nonneg_right hcard (show 0 ≤ 4*slotTotal gs f ∅ by positivity)] lemma finite_center_sum {X : Type*} (s : Finset X) (w H : X → ℝ) (a : ℝ) : (∑ x ∈ s, w x*(H x-a)^2) = (∑ x ∈ s, w x*(H x)^2) - 2*a*(∑ x ∈ s,w x*H x)+a^2*(∑ x ∈ s,w x) := by have he (x : X) : w x*(H x-a)^2 = w x*(H x)^2 - 2*a*(w x*H x)+a^2*w x := by ring simp_rw [he] rw [Finset.sum_add_distrib,Finset.sum_sub_distrib,← Finset.mul_sum,← Finset.mul_sum] lemma finite_center_at_mean {X : Type*} (s : Finset X) (w H : X → ℝ) (hz : (∑ x ∈ s,w x) ≠ 0) : (∑ x ∈ s, w x*(H x-(∑ y ∈ s,w y*H y)/(∑ y ∈ s,w y))^2) = (∑ x ∈ s,w x*(H x)^2) - (∑ x ∈ s,w x*H x)^2/(∑ x ∈ s,w x) := by rw [finite_center_sum] field_simp ; ring lemma finite_center_min {X : Type*} (s : Finset X) (w H : X → ℝ) (a : ℝ) (hz : 0 < ∑ x ∈ s,w x) : (∑ x ∈ s, w x*(H x-(∑ y ∈ s,w y*H y)/(∑ y ∈ s,w y))^2) ≤ ∑ x ∈ s,w x*(H x-a)^2 := by rw [finite_center_at_mean s w H (ne_of_gt hz),finite_center_sum] have hsq : 0 ≤ ((∑ x ∈ s,w x*H x)-a*(∑ x ∈ s,w x))^2 := sq_nonneg _ apply (mul_le_mul_iff_left₀ hz).mp field_simp nlinarith lemma plain_center_eq_variance (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hcover : pairSupport gs = Set.univ) (f H : Set Γ → ℝ) (hf : ∀ S, 0 < f S) : (∑ S ∈ Finset.univ.filter (PlainState gs), f S*(H S-plainMean gs f H)^2) = slotVariance gs f H ∅ := by have hz := slotTotal_pos gs f hf ∅ hgs rw [slotTotal_eq_plain_sum gs hgs hcover] at hz unfold plainMean rw [slotTotal_eq_plain_sum gs hgs hcover,slotTotal_eq_plain_sum gs hgs hcover, finite_center_at_mean _ _ _ (ne_of_gt hz),slotVariance_eq_plain_variance gs hgs hcover] lemma projection_center_decomposition (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hcover : pairSupport gs = Set.univ) (w : (Γ × Γ) → (Γ × Γ) → ℝ) (f H : Set Γ → ℝ) (hf : ∀ S, 0 < f S) : (∑ S ∈ chainStates gs, chainWeight gs w f S* (observableProjection gs f H S-plainMean gs f H)^2) = slotVariance gs f H ∅ + ∑ pr ∈ defectTypes gs, w pr.1 pr.2*slotDefect gs f ∅ pr.1 pr.2* (defectMean gs f H pr.1 pr.2-plainMean gs f H)^2 := by simp only [chainWeight,mul_assoc] rw [chain_sum_decomposition] congr 1 · rw [← plain_center_eq_variance gs hgs hcover f H hf] apply Finset.sum_congr rfl intro S hS rw [observableProjection_plain gs f H S (Finset.mem_filter.mp hS).2] · apply Finset.sum_congr rfl intro pr hm obtain ⟨hp,hr,hpr⟩ := (mem_defectTypes gs pr).mp hm rw [slotDefect_eq_defect_sum gs hgs hcover f pr.1 pr.2 hp hr hpr,Finset.sum_mul] congr 1 apply Finset.sum_congr rfl intro S hS rw [observableProjection_defect gs f H S (Finset.mem_filter.mp hS).2] noncomputable def chainMean (gs : List (Γ × Γ)) (w : (Γ × Γ) → (Γ × Γ) → ℝ) (f H : Set Γ → ℝ) : ℝ := (∑ S ∈ chainStates gs,chainWeight gs w f S*H S)/chainTotal gs w f noncomputable def chainVariance (gs : List (Γ × Γ)) (w : (Γ × Γ) → (Γ × Γ) → ℝ) (f H : Set Γ → ℝ) : ℝ := (∑ S ∈ chainStates gs,chainWeight gs w f S*(H S-chainMean gs w f H)^2)/chainTotal gs w f noncomputable def chainDirichlet (gs : List (Γ × Γ)) (w : (Γ × Γ) → (Γ × Γ) → ℝ) (f H : Set Γ → ℝ) : ℝ := restrictedEnergy (chainEdges gs) (chainConductance gs w f) H ∅ ∅/ (2*(gs.length:ℝ)^2*chainTotal gs w f) lemma projection_center_bound (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hcover : pairSupport gs = Set.univ) (w : (Γ × Γ) → (Γ × Γ) → ℝ) (hw : ∀ p r, 0 < w p r) (f H : Set Γ → ℝ) (hf : ∀ S, 0 < f S) (hsig : HasSlotSignature f) (hlower : ∀ p ∈ gs, ∀ r ∈ gs, p ≠ r → slotTotal gs f ∅/(4*slotDefect gs f ∅ p r) ≤ w p r) (hupper : ∀ p ∈ gs, ∀ r ∈ gs, p ≠ r → w p r ≤ 4*slotTotal gs f ∅/slotDefect gs f ∅ p r) : (∑ S ∈ chainStates gs, chainWeight gs w f S* (observableProjection gs f H S-plainMean gs f H)^2) ≤ ((gs.length:ℝ)*(1+8*(gs.length:ℝ))+4*((defectTypes gs).card:ℝ)*(8+32*(gs.length:ℝ)))* restrictedEnergy (chainEdges gs) (chainConductance gs w f) H ∅ ∅ := by rw [projection_center_decomposition gs hgs hcover w f H hf] have hp := transversal_variance_bound gs f H w hf hsig hgs hw hlower let D := restrictedEnergy (chainEdges gs) (chainConductance gs w f) H ∅ ∅ have hd : ∀ pr ∈ defectTypes gs, w pr.1 pr.2*slotDefect gs f ∅ pr.1 pr.2*(defectMean gs f H pr.1 pr.2-plainMean gs f H)^2 ≤ 4*(8+32*(gs.length:ℝ))*D := by intro pr hm obtain ⟨hp,hr,hpr⟩ := (mem_defectTypes gs pr).mp hm have hu := (le_div_iff₀ (slotDefect_pos gs f hf ∅ hgs pr.1 pr.2 hp hr hpr)).mp (hupper pr.1 hp pr.2 hr hpr) have ht := defect_mean_bound gs pr.1 pr.2 hgs hp hr hpr f H hf hsig w hw hlower change slotTotal gs f ∅*(defectMean gs f H pr.1 pr.2-plainMean gs f H)^2 ≤ _ at ht have hh := mul_le_mul_of_nonneg_right hu (sq_nonneg (defectMean gs f H pr.1 pr.2-plainMean gs f H)) dsimp only [D] linarith have hs := Finset.sum_le_sum (fun pr hpr => hd pr hpr) simp only [Finset.sum_const,nsmul_eq_mul] at hs dsimp only [D] at hs nlinarith theorem observable_poincare (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hne : gs ≠ []) (hcover : pairSupport gs = Set.univ) (w : (Γ × Γ) → (Γ × Γ) → ℝ) (hw : ∀ p r, 0 < w p r) (f H : Set Γ → ℝ) (hf : ∀ S, 0 < f S) (hsig : HasSlotSignature f) (hlower : ∀ p ∈ gs, ∀ r ∈ gs, p ≠ r → slotTotal gs f ∅/(4*slotDefect gs f ∅ p r) ≤ w p r) (hupper : ∀ p ∈ gs, ∀ r ∈ gs, p ≠ r → w p r ≤ 4*slotTotal gs f ∅/slotDefect gs f ∅ p r) : chainVariance gs w f (observableProjection gs f H) ≤ 2000*(gs.length:ℝ)^6*chainDirichlet gs w f H := by have hΛ := chainTotal_pos gs hgs hcover w f hf hw have hm := finite_center_min (chainStates gs) (chainWeight gs w f) (observableProjection gs f H) (plainMean gs f H) hΛ have hb := projection_center_bound gs hgs hcover w hw f H hf hsig hlower hupper let n : ℝ := gs.length let D := restrictedEnergy (chainEdges gs) (chainConductance gs w f) H ∅ ∅ have hD : 0 ≤ D := restrictedEnergy_nonneg _ _ _ _ _ (by intro ST _ exact le_min (mul_nonneg (chainMultiplier_pos gs w hw _).le (hf _).le) (mul_nonneg (chainMultiplier_pos gs w hw _).le (hf _).le)) have hn : 1 ≤ n := by dsimp only [n] exact_mod_cast List.length_pos_iff.mpr hne have hn0 : 0 < n := lt_of_lt_of_le zero_lt_one hn have hcard : ((defectTypes gs).card:ℝ) ≤ n^2 := by dsimp only [n] exact_mod_cast (show (defectTypes gs).card ≤ gs.length^2 by simpa [pow_two] using defectTypes_card_le gs) have hc : n*(1+8*n)+4*((defectTypes gs).card:ℝ)*(8+32*n) ≤ 1000*n^4 := by have hn2 : n ≤ n^2 := by nlinarith have hn3 : n^2 ≤ n^3 := by nlinarith [mul_le_mul_of_nonneg_left hn2 hn0.le] have hn4 : n^3 ≤ n^4 := by nlinarith [mul_le_mul_of_nonneg_left hn3 hn0.le] have hh := mul_le_mul_of_nonneg_right hcard (show 0 ≤ 4*(8+32*n) by positivity) nlinarith have hbound := (hm.trans hb).trans (mul_le_mul_of_nonneg_right hc hD) change chainVariance gs w f (observableProjection gs f H) ≤ 2000*n^6*(D/(2*n^2*chainTotal gs w f)) unfold chainVariance chainMean apply (div_le_iff₀ hΛ).mpr have he : 2000*n^6*(D/(2*n^2*chainTotal gs w f))*chainTotal gs w f = 1000*n^4*D := by field_simp ; ring rw [he] exact hbound end Observable section ChainGeometry open scoped BigOperators Classical variable {Γ : Type*} [sectionInstance54 : Fintype Γ] [sectionInstance55 : DecidableEq Γ] lemma pairSupport_ncard (ps : List (Γ × Γ)) (A : Set Γ) (hps : SlotsFresh ps A) : (A ∪ pairSupport ps).ncard = A.ncard+2*ps.length := by induction ps generalizing A with | nil => simp | cons p ps ih => have he : A ∪ pairSupport (p::ps) = (insert p.1 (insert p.2 A)) ∪ pairSupport ps := by rw [pairSupport_cons] ext x simp only [Set.mem_union,Set.mem_insert_iff] tauto rw [he,ih _ hps.2.2.2,Set.ncard_insert_of_notMem (by simpa only [Set.mem_insert_iff,not_or] using And.intro hps.1 hps.2.1), Set.ncard_insert_of_notMem hps.2.2.1,List.length_cons] omega lemma slots_ground_card (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hcover : pairSupport gs = Set.univ) : Fintype.card Γ = 2*gs.length := by have h := pairSupport_ncard gs ∅ hgs simpa [hcover,Set.ncard_univ,Nat.card_eq_fintype_card] using h lemma choiceVertices_ncard (ps : List (Γ × Γ)) (A S : Set Γ) (hps : SlotsFresh ps A) (hS : S ∈ choiceVertices ps A) : S.ncard = A.ncard+ps.length := by induction ps generalizing A with | nil => simp only [choiceVertices,Finset.mem_singleton] at hS subst S simp | cons p ps ih => rw [choiceVertices,Finset.mem_union] at hS rcases hS with hS | hS · have ht : SlotsFresh ps (insert p.1 A) := hps.2.2.2.mono (by intro x hx simp only [Set.mem_insert_iff] at hx ⊢ tauto) rw [ih _ ht hS,Set.ncard_insert_of_notMem hps.2.1,List.length_cons] omega · have ht : SlotsFresh ps (insert p.2 A) := hps.2.2.2.mono (Set.subset_insert _ _) rw [ih _ ht hS,Set.ncard_insert_of_notMem hps.2.2.1,List.length_cons] omega lemma PlainState.ncard {gs : List (Γ × Γ)} (hgs : SlotsFresh gs ∅) (hcover : pairSupport gs = Set.univ) {S : Set Γ} (hS : PlainState gs S) : S.ncard = gs.length := by have hm : S ∈ choiceVertices gs ∅ := by rw [choiceVertices_plain gs hgs hcover]; simp [hS] simpa using choiceVertices_ncard gs ∅ S hgs hm lemma DefectState.ncard {gs : List (Γ × Γ)} (hgs : SlotsFresh gs ∅) (hcover : pairSupport gs = Set.univ) {p r : Γ × Γ} {S : Set Γ} (hS : DefectState gs p r S) : S.ncard = gs.length := by let ps := (gs.erase p).erase r have hperm : gs.Perm (p::r::ps) := slots_perm_two hS.1 hS.2.1 hS.2.2.1 have hs := (SlotsFresh.perm hperm ∅).mp hgs have ht : SlotsFresh ps {r.1,r.2} := hs.2.2.2.2.2.2.mono (by intro x hx simp only [Set.mem_insert_iff,Set.mem_singleton_iff,Set.mem_empty_iff_false,or_false] at hx ⊢ tauto) have hm : S ∈ choiceVertices ps {r.1,r.2} := by rw [choiceVertices_defect gs hgs hcover p r hS.1 hS.2.1 hS.2.2.1] simp [hS] have hc := choiceVertices_ncard ps {r.1,r.2} S ht hm have hpair : ({r.1,r.2} : Set Γ).ncard = 2 := Set.ncard_pair hs.2.2.2.1 rw [hpair] at hc have hl := hperm.length_eq simp only [List.length_cons] at hl omega lemma ChainState.ncard {gs : List (Γ × Γ)} (hgs : SlotsFresh gs ∅) (hcover : pairSupport gs = Set.univ) {S : Set Γ} (hS : ChainState gs S) : S.ncard = gs.length := by rcases hS with hS | ⟨p,r,hS⟩ · exact hS.ncard hgs hcover · exact hS.ncard hgs hcover omit sectionInstance54 sectionInstance55 in lemma ExchangeAdjacent.symm [Fintype Γ] [DecidableEq Γ] {S T : Set Γ} (h : ExchangeAdjacent S T) : ExchangeAdjacent T S := by obtain ⟨A,a,b,hab,ha,hb,hS,hT⟩ := h exact ⟨A,b,a,hab.symm,hb,ha,hT,hS⟩ omit sectionInstance54 sectionInstance55 in lemma ExchangeAdjacent.ne [Fintype Γ] [DecidableEq Γ] {S T : Set Γ} (h : ExchangeAdjacent S T) : S ≠ T := by obtain ⟨A,a,b,hab,ha,hb,rfl,rfl⟩ := h intro he have hh : a ∈ insert b A := he ▸ Set.mem_insert a A exact (Set.mem_insert_iff.mp hh).elim hab ha omit sectionInstance54 sectionInstance55 in lemma ExchangeAdjacent.move [Fintype Γ] [DecidableEq Γ] {S T : Set Γ} (h : ExchangeAdjacent S T) : ∃ a ∈ S, ∃ b ∈ Sᶜ, T = insert b (S\{a}) := by obtain ⟨A,a,b,hab,ha,hb,rfl,rfl⟩ := h refine ⟨a,Set.mem_insert _ _,b,?_,?_⟩ · simpa only [Set.mem_compl_iff,Set.mem_insert_iff,not_or] using And.intro hab.symm hb · congr 1 ext x simp only [Set.mem_sdiff,Set.mem_insert_iff,Set.mem_singleton_iff] constructor · intro hx exact ⟨Or.inr hx,fun he => ha (he ▸ hx)⟩ · rintro ⟨hh,hn⟩ exact hh.resolve_left hn lemma exchange_neighbors_card (S : Set Γ) : (Finset.univ.filter (ExchangeAdjacent S)).card ≤ S.ncard*Sᶜ.ncard := by have hsub : Finset.univ.filter (ExchangeAdjacent S) ⊆ (S.toFinset ×ˢ Sᶜ.toFinset).image (fun ab => insert ab.2 (S\{ab.1})) := by intro T hT obtain ⟨a,ha,b,hb,rfl⟩ := (Finset.mem_filter.mp hT).2.move exact Finset.mem_image.mpr ⟨(a,b),by simpa only [Finset.mem_product,Set.mem_toFinset] using And.intro ha hb,rfl⟩ calc _ ≤ ((S.toFinset ×ˢ Sᶜ.toFinset).image (fun ab => insert ab.2 (S\{ab.1}))).card := Finset.card_le_card hsub _ ≤ (S.toFinset ×ˢ Sᶜ.toFinset).card := Finset.card_image_le _ = _ := by rw [Finset.card_product,← Set.ncard_eq_toFinset_card',← Set.ncard_eq_toFinset_card'] abbrev ChainIndex (gs : List (Γ × Γ)) := {S : Set Γ // ChainState gs S} lemma chain_neighbors_card (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hcover : pairSupport gs = Set.univ) (S : ChainIndex gs) : (Finset.univ.filter (fun T : ChainIndex gs => ExchangeAdjacent S.val T.val)).card ≤ gs.length^2 := by let e : ChainIndex gs → Set Γ := Subtype.val have he : Function.Injective e := Subtype.val_injective have hsub : (Finset.univ.filter (fun T : ChainIndex gs => ExchangeAdjacent S.val T.val)).image e ⊆ Finset.univ.filter (ExchangeAdjacent S.val) := by intro T hT obtain ⟨U,hU,hUT⟩ := Finset.mem_image.mp hT subst T exact Finset.mem_filter.mpr ⟨Finset.mem_univ _,(Finset.mem_filter.mp hU).2⟩ have hcompl : S.valᶜ.ncard = gs.length := by have hc := S.val.ncard_add_ncard_compl rw [Nat.card_eq_fintype_card,slots_ground_card gs hgs hcover,S.property.ncard hgs hcover] at hc omega calc _ = ((Finset.univ.filter (fun T : ChainIndex gs => ExchangeAdjacent S.val T.val)).image e).card := (Finset.card_image_of_injective _ he).symm _ ≤ (Finset.univ.filter (ExchangeAdjacent S.val)).card := Finset.card_le_card hsub _ ≤ S.val.ncard*S.valᶜ.ncard := exchange_neighbors_card _ _ = gs.length^2 := by rw [S.property.ncard hgs hcover,hcompl,pow_two] end ChainGeometry open scoped BigOperators Classical structure FiniteChain (X : Type*) [Fintype X] where P : X → X → ℝ π : X → ℝ positive : ∀ x, 0 < π x normalized : ∑ x, π x = 1 nonnegative : ∀ x y, 0 ≤ P x y stochastic : ∀ x, ∑ y, P x y = 1 reversible : ∀ x y, π x*P x y = π y*P y x lazy : ∀ x, 1/2 ≤ P x x namespace FiniteChain variable {X : Type*} [sectionInstance56 : Fintype X] (C : FiniteChain X) noncomputable def inner (f g : X → ℝ) : ℝ := ∑ x, C.π x*f x*g x noncomputable def apply (f : X → ℝ) (x : X) : ℝ := ∑ y, C.P x y*f y noncomputable def energy (f : X → ℝ) : ℝ := C.inner f (fun x => f x-C.apply f x) noncomputable def iterate (k : ℕ) (f : X → ℝ) : X → ℝ := Nat.iterate C.apply k f lemma inner_symm (f g : X → ℝ) : C.inner f g = C.inner g f := by unfold inner apply Finset.sum_congr rfl intro x _ ring lemma inner_add_right (f g h : X → ℝ) : C.inner f (fun x => g x+h x) = C.inner f g+C.inner f h := by simp [inner,mul_add,Finset.sum_add_distrib] lemma inner_sub_right (f g h : X → ℝ) : C.inner f (fun x => g x-h x) = C.inner f g-C.inner f h := by simp [inner,mul_sub,Finset.sum_sub_distrib] lemma inner_add_left (f g h : X → ℝ) : C.inner (fun x => f x+g x) h = C.inner f h+C.inner g h := by rw [inner_symm,inner_add_right,inner_symm C h f,inner_symm C h g] lemma inner_sum_right {J : Type*} (s : Finset J) (f : X → ℝ) (g : J → X → ℝ) : C.inner f (fun x => ∑ j ∈ s,g j x) = ∑ j ∈ s,C.inner f (g j) := by simp only [inner,Finset.mul_sum] exact Finset.sum_comm lemma inner_sum_left {J : Type*} (s : Finset J) (f : J → X → ℝ) (g : X → ℝ) : C.inner (fun x => ∑ j ∈ s,f j x) g = ∑ j ∈ s,C.inner (f j) g := by rw [inner_symm,inner_sum_right] apply Finset.sum_congr rfl intro j _ exact C.inner_symm _ _ lemma inner_nonneg (f : X → ℝ) : 0 ≤ C.inner f f := by apply Finset.sum_nonneg intro x _ nlinarith [C.positive x,sq_nonneg (f x)] lemma apply_add (f g : X → ℝ) : C.apply (fun x => f x+g x) = fun x => C.apply f x+C.apply g x := by funext x simp [apply,mul_add,Finset.sum_add_distrib] lemma apply_sum {J : Type*} (s : Finset J) (f : J → X → ℝ) : C.apply (fun x => ∑ j ∈ s,f j x) = fun x => ∑ j ∈ s,C.apply (f j) x := by funext x simp only [apply,Finset.mul_sum] exact Finset.sum_comm lemma apply_const (a : ℝ) : C.apply (fun _ => a) = fun _ => a := by funext x simp [apply,← Finset.sum_mul,C.stochastic] lemma stationary (y : X) : ∑ x, C.π x*C.P x y = C.π y := by simp_rw [C.reversible] rw [← Finset.mul_sum,C.stochastic,mul_one] lemma apply_selfAdjoint (f g : X → ℝ) : C.inner f (C.apply g) = C.inner (C.apply f) g := by unfold inner apply simp only [Finset.mul_sum,Finset.sum_mul] rw [Finset.sum_comm] apply Finset.sum_congr rfl intro y _ apply Finset.sum_congr rfl intro x _ have h := C.reversible x y calc _ = (C.π x*C.P x y)*(f x*g y) := by ring _ = (C.π y*C.P y x)*(f x*g y) := by rw [h] _ = _ := by ring lemma energy_eq (f : X → ℝ) : C.energy f = (∑ x, ∑ y, C.π x*C.P x y*(f x-f y)^2)/2 := by have h₁ : (∑ x,∑ y,C.π x*C.P x y*(f x)^2) = C.inner f f := by simp_rw [mul_assoc,← Finset.mul_sum,← Finset.sum_mul,C.stochastic,one_mul] unfold inner apply Finset.sum_congr rfl intro x _ ring have h₂ : (∑ x,∑ y,C.π x*C.P x y*(f y)^2) = C.inner f f := by rw [Finset.sum_comm] simp_rw [← Finset.sum_mul,C.stationary] unfold inner apply Finset.sum_congr rfl intro x _ ring have h₃ : (∑ x,∑ y,C.π x*C.P x y*(f x*f y)) = C.inner f (C.apply f) := by unfold inner apply simp only [Finset.mul_sum] apply Finset.sum_congr rfl intro x _ apply Finset.sum_congr rfl intro y _ ring have he (x y : X) : C.π x*C.P x y*(f x-f y)^2 = C.π x*C.P x y*(f x)^2+C.π x*C.P x y*(f y)^2-2*(C.π x*C.P x y*(f x*f y)) := by ring simp_rw [he,Finset.sum_sub_distrib,Finset.sum_add_distrib,← Finset.mul_sum] rw [h₁,h₂,h₃,energy,inner_sub_right] ring lemma energy_nonneg (f : X → ℝ) : 0 ≤ C.energy f := by rw [C.energy_eq] apply div_nonneg _ (by norm_num) apply Finset.sum_nonneg intro x _ apply Finset.sum_nonneg intro y _ exact mul_nonneg (mul_nonneg (C.positive x).le (C.nonnegative x y)) (sq_nonneg _) lemma energy_le_inner (f : X → ℝ) : C.energy f ≤ C.inner f f := by classical have ho (x : X) : ∑ y ∈ Finset.univ.erase x,C.P x y ≤ 1/2 := by have h := Finset.sum_erase_add Finset.univ (fun y => C.P x y) (Finset.mem_univ x) rw [C.stochastic] at h linarith [C.lazy x] have hbound : (∑ x,∑ y,C.π x*C.P x y*(f x-f y)^2) ≤ ∑ x,∑ y ∈ Finset.univ.erase x,2*(C.π x*C.P x y*(f x)^2+C.π x*C.P x y*(f y)^2) := by apply Finset.sum_le_sum intro x _ rw [← Finset.sum_erase_add _ _ (Finset.mem_univ x)] simp only [sub_self,zero_pow (by decide : 2 ≠ 0),mul_zero,add_zero] apply Finset.sum_le_sum intro y _ have h := mul_le_mul_of_nonneg_left (show (f x-f y)^2 ≤ 2*((f x)^2+(f y)^2) by nlinarith [sq_nonneg (f x+f y)]) (mul_nonneg (C.positive x).le (C.nonnegative x y)) nlinarith have hs (x : X) : (∑ y ∈ Finset.univ.erase x,C.π x*C.P x y*(f x)^2) ≤ (C.π x*(f x)^2)/2 := by calc _ = (C.π x*(f x)^2)*(∑ y ∈ Finset.univ.erase x,C.P x y) := by rw [Finset.mul_sum] apply Finset.sum_congr rfl intro y _ ring _ ≤ _ := by nlinarith [mul_le_mul_of_nonneg_left (ho x) (mul_nonneg (C.positive x).le (sq_nonneg (f x)))] have hswap : (∑ x,∑ y ∈ Finset.univ.erase x,C.π x*C.P x y*(f y)^2) = ∑ x,∑ y ∈ Finset.univ.erase x,C.π x*C.P x y*(f x)^2 := by simp only [Finset.sum_erase_eq_sub (Finset.mem_univ _)] rw [Finset.sum_sub_distrib,Finset.sum_sub_distrib] congr 1 rw [Finset.sum_comm] apply Finset.sum_congr rfl intro x _ apply Finset.sum_congr rfl intro y _ rw [C.reversible] have hsum := Finset.sum_le_sum (fun x (_ : x ∈ Finset.univ) => hs x) have heq : (∑ x,C.π x*(f x)^2/2) = C.inner f f/2 := by rw [← Finset.sum_div] congr 1 unfold inner apply Finset.sum_congr rfl intro x _ ring rw [heq] at hsum simp_rw [← Finset.mul_sum,Finset.sum_add_distrib] at hbound rw [hswap] at hbound rw [C.energy_eq] linarith lemma apply_positive (f : X → ℝ) : 0 ≤ C.inner f (C.apply f) := by have h := C.energy_le_inner f rw [energy,inner_sub_right] at h linarith @[simp] lemma iterate_zero (f : X → ℝ) : C.iterate 0 f = f := rfl lemma iterate_succ (k : ℕ) (f : X → ℝ) : C.iterate (k+1) f = C.apply (C.iterate k f) := by exact Function.iterate_succ_apply' C.apply k f lemma iterate_add (k l : ℕ) (f : X → ℝ) : C.iterate (k+l) f = C.iterate k (C.iterate l f) := by exact Function.iterate_add_apply C.apply k l f lemma iterate_selfAdjoint (k : ℕ) (f g : X → ℝ) : C.inner f (C.iterate k g) = C.inner (C.iterate k f) g := by induction k generalizing f g with | zero => rfl | succ k ih => rw [C.iterate_succ,C.apply_selfAdjoint,ih] change C.inner (C.iterate k (C.iterate 1 f)) g = _ rw [← C.iterate_add] lemma covariance_nonneg (k : ℕ) (f : X → ℝ) : 0 ≤ C.inner f (C.iterate k f) := by have hk : k = k/2+k/2 ∨ k = k/2+(k/2+1) := by have := Nat.mod_add_div k 2 have := Nat.mod_lt k (by decide : 0 < 2) omega rcases hk with hk | hk · nth_rw 1 [hk] rw [C.iterate_add,C.iterate_selfAdjoint] exact C.inner_nonneg _ · nth_rw 1 [hk] rw [C.iterate_add,C.iterate_selfAdjoint,C.iterate_succ] exact C.apply_positive _ noncomputable def partialResolvent (N : ℕ) (f : X → ℝ) (x : X) : ℝ := ∑ k ∈ Finset.range N,C.iterate k f x lemma partialResolvent_zero (f : X → ℝ) : C.partialResolvent 0 f = fun _ => 0 := by funext x simp [partialResolvent] lemma partialResolvent_succ (N : ℕ) (f : X → ℝ) : C.partialResolvent (N+1) f = fun x => C.partialResolvent N f x+C.iterate N f x := by funext x exact Finset.sum_range_succ _ _ lemma partialResolvent_residual (N : ℕ) (f : X → ℝ) : (fun x => C.partialResolvent N f x-C.apply (C.partialResolvent N f) x) = fun x => f x-C.iterate N f x := by induction N with | zero => rw [C.partialResolvent_zero,C.apply_const]; simp | succ N ih => rw [C.partialResolvent_succ,C.apply_add,C.iterate_succ] funext x have hh := congrFun ih x dsimp only at hh ⊢ linarith lemma partialResolvent_inner (N : ℕ) (f : X → ℝ) : C.inner f (C.partialResolvent N f) = ∑ k ∈ Finset.range N,C.inner f (C.iterate k f) := by exact C.inner_sum_right _ _ _ lemma partialResolvent_energy_le (N : ℕ) (f : X → ℝ) : C.energy (C.partialResolvent N f) ≤ C.inner f (C.partialResolvent N f) := by rw [energy,C.partialResolvent_residual,C.inner_sub_right,C.inner_symm (C.partialResolvent N f) f] have hh : 0 ≤ C.inner (C.partialResolvent N f) (C.iterate N f) := by change 0 ≤ C.inner (fun x => ∑ k ∈ Finset.range N,C.iterate k f x) (C.iterate N f) rw [C.inner_sum_left] apply Finset.sum_nonneg intro k _ rw [← C.iterate_selfAdjoint,← C.iterate_add] exact C.covariance_nonneg _ f linarith theorem covariance_sum_bound (g : X → ℝ) (K : ℝ) (hK : 0 ≤ K) (hdual : ∀ H, (C.inner g H)^2 ≤ K*C.inner g g*C.energy H) (N : ℕ) : (∑ k ∈ Finset.range N,C.inner g (C.iterate k g)) ≤ K*C.inner g g := by rw [← C.partialResolvent_inner] have h := hdual (C.partialResolvent N g) have he := C.partialResolvent_energy_le N g have hnon : 0 ≤ K*C.inner g g := mul_nonneg hK (C.inner_nonneg g) have hb := mul_le_mul_of_nonneg_left he hnon nlinarith noncomputable def pathExpectation : ℕ → X → (List X → ℝ) → ℝ | 0,x,F => F [x] | N+1,x,F => ∑ y,C.P x y*pathExpectation N y (fun l => F (x::l)) lemma pathExpectation_nonneg (N : ℕ) (x : X) (F : List X → ℝ) (hF : ∀ l,0 ≤ F l) : 0 ≤ C.pathExpectation N x F := by induction N generalizing x F with | zero => exact hF _ | succ N ih => apply Finset.sum_nonneg intro y _ exact mul_nonneg (C.nonnegative x y) (ih y _ (fun l => hF _)) lemma pathExpectation_add (N : ℕ) (x : X) (F G : List X → ℝ) : C.pathExpectation N x (fun l => F l+G l) = C.pathExpectation N x F+C.pathExpectation N x G := by induction N generalizing x F G with | zero => rfl | succ N ih => simp [pathExpectation,ih,mul_add,Finset.sum_add_distrib] lemma pathExpectation_mul (N : ℕ) (x : X) (a : ℝ) (F : List X → ℝ) : C.pathExpectation N x (fun l => a*F l) = a*C.pathExpectation N x F := by induction N generalizing x F with | zero => rfl | succ N ih => simp [pathExpectation,ih,Finset.mul_sum,mul_left_comm] lemma pathExpectation_const (N : ℕ) (x : X) (a : ℝ) : C.pathExpectation N x (fun _ => a) = a := by induction N generalizing x with | zero => rfl | succ N ih => simp [pathExpectation,ih,← Finset.sum_mul,C.stochastic] lemma pathExpectation_congr (N : ℕ) (x : X) (F G : List X → ℝ) (hFG : ∀ l,F l=G l) : C.pathExpectation N x F = C.pathExpectation N x G := by congr 1 funext l exact hFG l noncomputable def pathSum (g : X → ℝ) (l : List X) : ℝ := (l.map g).sum noncomputable def squareMoment (g : X → ℝ) (N : ℕ) (x : X) : ℝ := if N=0 then 0 else C.pathExpectation (N-1) x (fun l => (pathSum g l)^2) omit sectionInstance56 in lemma pathSum_cons [Fintype X] (g : X → ℝ) (x : X) (l : List X) : pathSum g (x::l) = g x+pathSum g l := rfl lemma pathExpectation_sum (g : X → ℝ) (N : ℕ) (x : X) : C.pathExpectation N x (pathSum g) = C.partialResolvent (N+1) g x := by induction N generalizing x with | zero => simp [pathExpectation,pathSum,partialResolvent] | succ N ih => have hc (y : X) : C.pathExpectation N y (fun l => pathSum g (x::l)) = g x+C.partialResolvent (N+1) g y := by simp only [pathSum_cons] rw [C.pathExpectation_add,C.pathExpectation_const,ih] simp only [pathExpectation,hc,mul_add,Finset.sum_add_distrib,← Finset.sum_mul,C.stochastic,one_mul] have hh := congrFun (C.partialResolvent_residual (N+1) g) x change g x+C.apply (C.partialResolvent (N+1) g) x = _ rw [C.partialResolvent_succ (N+1)] dsimp only at hh ⊢ linarith lemma squareMoment_zero (g : X → ℝ) (x : X) : C.squareMoment g 0 x = 0 := rfl lemma squareMoment_succ (g : X → ℝ) (N : ℕ) (x : X) : C.squareMoment g (N+1) x = (g x)^2 + 2*g x*C.apply (C.partialResolvent N g) x+C.apply (C.squareMoment g N) x := by cases N with | zero => simp [squareMoment,pathExpectation,pathSum,partialResolvent,apply] | succ N => simp only [squareMoment,Nat.succ_ne_zero,ite_false, Nat.add_sub_cancel,pathExpectation] have he (y : X) : C.pathExpectation N y (fun l => (pathSum g (x::l))^2) = (g x)^2+2*g x*C.partialResolvent (N+1) g y+ C.pathExpectation N y (fun l => (pathSum g l)^2) := by calc _ = C.pathExpectation N y (fun l => (g x)^2+2*g x*pathSum g l+(pathSum g l)^2) := by apply C.pathExpectation_congr intro l rw [pathSum_cons] ring _ = _ := by rw [C.pathExpectation_add,C.pathExpectation_add,C.pathExpectation_const, C.pathExpectation_mul,C.pathExpectation_sum] simp only [he,mul_add,Finset.sum_add_distrib,← Finset.sum_mul,C.stochastic,one_mul] unfold apply congr 1 rw [Finset.mul_sum] congr 1 apply Finset.sum_congr rfl intro y _ ring lemma squareMoment_nonneg (g : X → ℝ) (N : ℕ) (x : X) : 0 ≤ C.squareMoment g N x := by unfold squareMoment split_ifs · exact le_rfl · exact C.pathExpectation_nonneg _ x _ (fun l => sq_nonneg _) lemma stationary_apply (f : X → ℝ) : ∑ x,C.π x*C.apply f x = ∑ x,C.π x*f x := by unfold apply simp only [Finset.mul_sum] rw [Finset.sum_comm] apply Finset.sum_congr rfl intro y _ simp_rw [← mul_assoc,← Finset.sum_mul,C.stationary] lemma stationary_squareMoment_succ (g : X → ℝ) (N : ℕ) : (∑ x,C.π x*C.squareMoment g (N+1) x) = (∑ x,C.π x*C.squareMoment g N x)+ C.inner g g+2*∑ k ∈ Finset.range N,C.inner g (C.iterate (k+1) g) := by simp_rw [C.squareMoment_succ,mul_add,Finset.sum_add_distrib] rw [C.stationary_apply] have h₁ : (∑ x,C.π x*(g x)^2) = C.inner g g := by unfold inner apply Finset.sum_congr rfl intro x _ ring have h₂ : (∑ x,C.π x*(2*g x*C.apply (C.partialResolvent N g) x)) = 2*C.inner g (C.apply (C.partialResolvent N g)) := by unfold inner rw [Finset.mul_sum] apply Finset.sum_congr rfl intro x _ ring rw [h₁,h₂] have hh : C.apply (C.partialResolvent N g) = fun x => ∑ k ∈ Finset.range N,C.iterate (k+1) g x := by change C.apply (fun x => ∑ k ∈ Finset.range N,C.iterate k g x) = _ rw [C.apply_sum] simp_rw [C.iterate_succ] rw [hh,C.inner_sum_right] ring theorem stationary_squareMoment_bound (g : X → ℝ) (K : ℝ) (hK : 0 ≤ K) (hdual : ∀ H, (C.inner g H)^2 ≤ K*C.inner g g*C.energy H) (N : ℕ) : (∑ x,C.π x*C.squareMoment g N x) ≤ 2*N*K*C.inner g g := by induction N with | zero => simp [squareMoment] | succ N ih => rw [C.stationary_squareMoment_succ] have hc := C.covariance_sum_bound g K hK hdual (N+1) have hh : (∑ k ∈ Finset.range (N+1),C.inner g (C.iterate k g)) = C.inner g g+ ∑ k ∈ Finset.range N,C.inner g (C.iterate (k+1) g) := by rw [Finset.sum_range_succ'] simp [add_comm] rw [hh] at hc have hg := C.inner_nonneg g push_cast nlinarith theorem warm_squareMoment_bound (g : X → ℝ) (K U : ℝ) (hK : 0 ≤ K) (hU : 0 ≤ U) (hdual : ∀ H, (C.inner g H)^2 ≤ K*C.inner g g*C.energy H) (ν : X → ℝ) (hwarm : ∀ x,ν x ≤ U*C.π x) (N : ℕ) (hN : 0 < N) : (∑ x,ν x*C.squareMoment g N x)/(N:ℝ)^2 ≤ 2*U*K*C.inner g g/N := by have hs : (∑ x,ν x*C.squareMoment g N x) ≤ U*∑ x,C.π x*C.squareMoment g N x := by rw [Finset.mul_sum] apply Finset.sum_le_sum intro x _ simpa only [mul_assoc] using mul_le_mul_of_nonneg_right (hwarm x) (C.squareMoment_nonneg g N x) have hb := mul_le_mul_of_nonneg_left (C.stationary_squareMoment_bound g K hK hdual N) hU have hn : (0:ℝ) < N := by exact_mod_cast hN apply (div_le_iff₀ (sq_pos_of_pos hn)).mpr have he : 2*U*K*C.inner g g/(N:ℝ)*(N:ℝ)^2 = U*(2*(N:ℝ)*K*C.inner g g) := by field_simp rw [he] exact hs.trans hb variable [DecidableEq X] noncomputable def ofMoves (π : X → ℝ) (m : X → X → ℝ) (hπ : ∀ x,0 < π x) (hπsum : ∑ x,π x = 1) (hm : ∀ x y,0 ≤ m x y) (hrow : ∀ x,∑ y,m x y ≤ 1/2) (hrev : ∀ x y,π x*m x y = π y*m y x) : FiniteChain X where P x y := m x y+if x=y then 1-∑ z,m x z else 0 π := π positive := hπ normalized := hπsum nonnegative x y := by split_ifs · linarith [hm x y,hrow x] · simpa using hm x y stochastic x := by simp [Finset.sum_add_distrib] reversible x y := by by_cases h : x=y · subst y; rfl · simp [h,Ne.symm h,hrev] lazy x := by simp only [ite_true]; linarith [hm x x,hrow x] lemma ofMoves_energy (π : X → ℝ) (m : X → X → ℝ) (hπ : ∀ x,0 < π x) (hπsum : ∑ x,π x = 1) (hm : ∀ x y,0 ≤ m x y) (hrow : ∀ x,∑ y,m x y ≤ 1/2) (hrev : ∀ x y,π x*m x y = π y*m y x) (f : X → ℝ) : (ofMoves π m hπ hπsum hm hrow hrev).energy f = (∑ x,∑ y,π x*m x y*(f x-f y)^2)/2 := by rw [energy_eq] congr 1 apply Finset.sum_congr rfl intro x _ apply Finset.sum_congr rfl intro y _ change π x*(m x y+if x=y then _ else _)*(f x-f y)^2 = _ by_cases h : x=y · subst y; simp · simp [h] end FiniteChain section Metropolis open scoped BigOperators Classical variable {Γ : Type*} [Fintype Γ] [sectionInstance59 : DecidableEq Γ] lemma chainWeight_pos (gs : List (Γ × Γ)) (w : (Γ × Γ) → (Γ × Γ) → ℝ) (f : Set Γ → ℝ) (hw : ∀ p r,0 < w p r) (hf : ∀ S,0 < f S) (S : Set Γ) : 0 < chainWeight gs w f S := mul_pos (chainMultiplier_pos gs w hw S) (hf S) omit sectionInstance59 in lemma chain_sum_subtype [DecidableEq Γ] (gs : List (Γ × Γ)) (g : Set Γ → ℝ) : (∑ S ∈ chainStates gs,g S) = ∑ S : ChainIndex gs,g S.val := by exact Finset.sum_subtype _ (by intro S; simp [chainStates]) g noncomputable def metropolisMove (gs : List (Γ × Γ)) (w : (Γ × Γ) → (Γ × Γ) → ℝ) (f : Set Γ → ℝ) (S T : ChainIndex gs) : ℝ := if ExchangeAdjacent S.val T.val then min (chainWeight gs w f S.val) (chainWeight gs w f T.val)/ (2*(gs.length:ℝ)^2*chainWeight gs w f S.val) else 0 lemma metropolisMove_nonneg (gs : List (Γ × Γ)) (w : (Γ × Γ) → (Γ × Γ) → ℝ) (f : Set Γ → ℝ) (hw : ∀ p r,0 < w p r) (hf : ∀ S,0 < f S) (S T : ChainIndex gs) : 0 ≤ metropolisMove gs w f S T := by have hS := chainWeight_pos gs w f hw hf S.val unfold metropolisMove split_ifs · exact div_nonneg (le_min (chainWeight_pos gs w f hw hf _).le (chainWeight_pos gs w f hw hf _).le) (by positivity) · rfl lemma metropolisMove_row (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hne : gs ≠ []) (hcover : pairSupport gs = Set.univ) (w : (Γ × Γ) → (Γ × Γ) → ℝ) (f : Set Γ → ℝ) (hw : ∀ p r,0 < w p r) (hf : ∀ S,0 < f S) (S : ChainIndex gs) : ∑ T,metropolisMove gs w f S T ≤ 1/2 := by have hS := chainWeight_pos gs w f hw hf S.val have hn : (0:ℝ) < gs.length := by exact_mod_cast List.length_pos_iff.mpr hne have hinc (T : ChainIndex gs) : metropolisMove gs w f S T ≤ if ExchangeAdjacent S.val T.val then 1/(2*(gs.length:ℝ)^2) else 0 := by unfold metropolisMove split_ifs · apply (div_le_iff₀ (by positivity : 0 < 2*(gs.length:ℝ)^2*chainWeight gs w f S.val)).mpr have he : 1/(2*(gs.length:ℝ)^2)*(2*(gs.length:ℝ)^2*chainWeight gs w f S.val) = chainWeight gs w f S.val := by field_simp rw [he] exact min_le_left _ _ · rfl have hs := Finset.sum_le_sum (fun T (_ : T ∈ Finset.univ) => hinc T) have hc : ((Finset.univ.filter (fun T : ChainIndex gs => ExchangeAdjacent S.val T.val)).card:ℝ) ≤ (gs.length:ℝ)^2 := by exact_mod_cast chain_neighbors_card gs hgs hcover S have he : (gs.length:ℝ)^2*(1/(2*(gs.length:ℝ)^2)) = 1/2 := by field_simp calc _ ≤ _ := hs _ = ((Finset.univ.filter (fun T : ChainIndex gs => ExchangeAdjacent S.val T.val)).card:ℝ)*(1/(2*(gs.length:ℝ)^2)) := by rw [← Finset.sum_filter]; simp _ ≤ (gs.length:ℝ)^2*(1/(2*(gs.length:ℝ)^2)) := mul_le_mul_of_nonneg_right hc (by positivity) _ = _ := he lemma metropolisMove_balanced (gs : List (Γ × Γ)) (w : (Γ × Γ) → (Γ × Γ) → ℝ) (f : Set Γ → ℝ) (hw : ∀ p r,0 < w p r) (hf : ∀ S,0 < f S) (S T : ChainIndex gs) : (chainWeight gs w f S.val/chainTotal gs w f)*metropolisMove gs w f S T = (chainWeight gs w f T.val/chainTotal gs w f)*metropolisMove gs w f T S := by have hs := (chainWeight_pos gs w f hw hf S.val).ne' have ht := (chainWeight_pos gs w f hw hf T.val).ne' by_cases h : ExchangeAdjacent S.val T.val · simp only [metropolisMove,ite_eq_left h,ite_eq_left h.symm] rw [min_comm (chainWeight gs w f T.val)] field_simp · have hh : ¬ ExchangeAdjacent T.val S.val := fun hh => h hh.symm simp [metropolisMove,h,hh] noncomputable def metropolisChain (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hne : gs ≠ []) (hcover : pairSupport gs = Set.univ) (w : (Γ × Γ) → (Γ × Γ) → ℝ) (f : Set Γ → ℝ) (hw : ∀ p r,0 < w p r) (hf : ∀ S,0 < f S) : FiniteChain (ChainIndex gs) := FiniteChain.ofMoves (fun S => chainWeight gs w f S.val/chainTotal gs w f) (metropolisMove gs w f) (fun S => div_pos (chainWeight_pos gs w f hw hf S.val) (chainTotal_pos gs hgs hcover w f hf hw)) (by rw [← Finset.sum_div,← chain_sum_subtype]; exact div_self (chainTotal_pos gs hgs hcover w f hf hw).ne') (metropolisMove_nonneg gs w f hw hf) (metropolisMove_row gs hgs hne hcover w f hw hf) (metropolisMove_balanced gs w f hw hf) lemma chainEdges_sum (gs : List (Γ × Γ)) (g : (Set Γ × Set Γ) → ℝ) : (∑ ST ∈ chainEdges gs,g ST) = ∑ S : ChainIndex gs,∑ T : ChainIndex gs, if ExchangeAdjacent S.val T.val then g (S.val,T.val) else 0 := by calc _ = ∑ S ∈ chainStates gs,∑ T ∈ chainStates gs, if ExchangeAdjacent S T then g (S,T) else 0 := by simp only [chainEdges,chainStates,Finset.sum_filter,Fintype.sum_prod_type] apply Finset.sum_congr rfl intro S _ by_cases hs : ChainState gs S · simp only [hs,true_and,ite_true] apply Finset.sum_congr rfl intro T _ by_cases ht : ChainState gs T <;> simp [ht] · simp [hs] _ = _ := by rw [chain_sum_subtype] apply Finset.sum_congr rfl intro S _ exact chain_sum_subtype gs _ lemma restrictedEnergy_chain_eq (gs : List (Γ × Γ)) (w : (Γ × Γ) → (Γ × Γ) → ℝ) (f H : Set Γ → ℝ) : restrictedEnergy (chainEdges gs) (chainConductance gs w f) H ∅ ∅ = (∑ S : ChainIndex gs, ∑ T : ChainIndex gs, if ExchangeAdjacent S.val T.val then min (chainWeight gs w f S.val) (chainWeight gs w f T.val)*(H S.val-H T.val)^2 else 0)/2 := by unfold restrictedEnergy simp only [EdgeRespects,Respects,Set.empty_subset,Set.empty_disjoint,and_self,ite_true] rw [chainEdges_sum] rfl theorem metropolisChain_energy (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hne : gs ≠ []) (hcover : pairSupport gs = Set.univ) (w : (Γ × Γ) → (Γ × Γ) → ℝ) (f H : Set Γ → ℝ) (hw : ∀ p r,0 < w p r) (hf : ∀ S,0 < f S) : (metropolisChain gs hgs hne hcover w f hw hf).energy (fun S => H S.val) = chainDirichlet gs w f H := by unfold metropolisChain rw [FiniteChain.ofMoves_energy] have he (S T : ChainIndex gs) : (chainWeight gs w f S.val/chainTotal gs w f)*metropolisMove gs w f S T*(H S.val-H T.val)^2 = (if ExchangeAdjacent S.val T.val then min (chainWeight gs w f S.val) (chainWeight gs w f T.val)*(H S.val-H T.val)^2 else 0)/ (2*(gs.length:ℝ)^2*chainTotal gs w f) := by have hs := (chainWeight_pos gs w f hw hf S.val).ne' unfold metropolisMove split_ifs · field_simp · simp simp_rw [he,← Finset.sum_div] rw [chainDirichlet,restrictedEnergy_chain_eq] ring end Metropolis namespace FiniteChain variable {X : Type*} [Fintype X] (C : FiniteChain X) lemma inner_cauchy (f g : X → ℝ) : (C.inner f g)^2 ≤ C.inner f f*C.inner g g := by have he (f g : X → ℝ) : (∑ x,(Real.sqrt (C.π x)*f x)*(Real.sqrt (C.π x)*g x)) = C.inner f g := by unfold inner apply Finset.sum_congr rfl intro x _ have hs := Real.sq_sqrt (C.positive x).le calc _ = (Real.sqrt (C.π x))^2*f x*g x := by ring _ = _ := by rw [hs] have hf (f : X → ℝ) : (∑ x,(Real.sqrt (C.π x)*f x)^2) = C.inner f f := by simpa only [pow_two] using he f f have h := Finset.sum_mul_sq_le_sq_mul_sq Finset.univ (fun x => Real.sqrt (C.π x)*f x) (fun x => Real.sqrt (C.π x)*g x) rwa [he,hf,hf] at h noncomputable def mean (f : X → ℝ) : ℝ := ∑ x,C.π x*f x noncomputable def variance (f : X → ℝ) : ℝ := C.inner (fun x => f x-C.mean f) (fun x => f x-C.mean f) lemma centered_mean (f : X → ℝ) : C.mean (fun x => f x-C.mean f) = 0 := by unfold mean simp [mul_sub,Finset.sum_sub_distrib,← Finset.sum_mul,C.normalized] lemma inner_center_right (f g : X → ℝ) (hf : C.mean f = 0) (a : ℝ) : C.inner f (fun x => g x-a) = C.inner f g := by rw [C.inner_sub_right] have hz : C.inner f (fun _ => a) = 0 := by change (∑ x,C.π x*f x*a) = 0 rw [← Finset.sum_mul] change C.mean f*a = 0 rw [hf,zero_mul] rw [hz,sub_zero] end FiniteChain section ProjectionBridge open scoped BigOperators Classical variable {Γ : Type*} [sectionInstance61 : Fintype Γ] [sectionInstance62 : DecidableEq Γ] def ClassObservable (gs : List (Γ × Γ)) (G : Set Γ → ℝ) : Prop := ∀ p r S T, DefectState gs p r S → DefectState gs p r T → G S = G T lemma projection_classObservable (gs : List (Γ × Γ)) (f G : Set Γ → ℝ) : ClassObservable gs (observableProjection gs f G) := by intro p r S T hS hT rw [observableProjection_defect gs f G S hS,observableProjection_defect gs f G T hT] omit sectionInstance61 sectionInstance62 in lemma ClassObservable.sub_const [Fintype Γ] [DecidableEq Γ] {gs : List (Γ × Γ)} {G : Set Γ → ℝ} (hG : ClassObservable gs G) (a : ℝ) : ClassObservable gs (fun S => G S-a) := by intro p r S T hS hT dsimp only rw [hG p r S T hS hT] lemma defect_pairing_projection (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hcover : pairSupport gs = Set.univ) (f G H : Set Γ → ℝ) (hf : ∀ S,0 < f S) (hG : ClassObservable gs G) (p r : Γ × Γ) (hp : p ∈ gs) (hr : r ∈ gs) (hpr : p ≠ r) : (∑ S ∈ Finset.univ.filter (DefectState gs p r), f S*G S*H S) = ∑ S ∈ Finset.univ.filter (DefectState gs p r), f S*G S*observableProjection gs f H S := by let t := Finset.univ.filter (DefectState gs p r) have hz := slotDefect_pos gs f hf ∅ hgs p r hp hr hpr rw [slotDefect_eq_defect_sum gs hgs hcover f p r hp hr hpr] at hz have ht : t.Nonempty := by by_contra h have he : t = ∅ := Finset.not_nonempty_iff_eq_empty.mp h change 0 < ∑ S ∈ t,f S at hz rw [he,Finset.sum_empty] at hz exact lt_irrefl _ hz obtain ⟨T,hT⟩ := ht have hTp : DefectState gs p r T := (Finset.mem_filter.mp hT).2 have hc (S : Set Γ) (hS : S ∈ t) : G S = G T := hG p r S T (Finset.mem_filter.mp hS).2 hTp change (∑ S ∈ t,f S*G S*H S) = ∑ S ∈ t,f S*G S*observableProjection gs f H S calc _ = G T*(∑ S ∈ t,f S*H S) := by rw [Finset.mul_sum] apply Finset.sum_congr rfl intro S hS rw [hc S hS]; ring _ = G T*((∑ S ∈ t,f S)*defectMean gs f H p r) := by congr 1 unfold defectMean rw [slotDefect_eq_defect_sum gs hgs hcover f p r hp hr hpr, slotDefect_eq_defect_sum gs hgs hcover (fun S => f S*H S) p r hp hr hpr] change _ = (∑ S ∈ t,f S)*((∑ S ∈ t,f S*H S)/(∑ S ∈ t,f S)) have hzt : (∑ S ∈ t,f S) ≠ 0 := hz.ne' field_simp [hzt] _ = _ := by rw [Finset.sum_mul,Finset.mul_sum] apply Finset.sum_congr rfl intro S hS rw [hc S hS,observableProjection_defect gs f H S (Finset.mem_filter.mp hS).2] ring lemma chain_pairing_projection (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hcover : pairSupport gs = Set.univ) (w : (Γ × Γ) → (Γ × Γ) → ℝ) (f G H : Set Γ → ℝ) (hf : ∀ S,0 < f S) (hG : ClassObservable gs G) : (∑ S ∈ chainStates gs,chainWeight gs w f S*G S*H S) = ∑ S ∈ chainStates gs,chainWeight gs w f S*G S*observableProjection gs f H S := by simp only [chainWeight,mul_assoc] rw [chain_sum_decomposition,chain_sum_decomposition] congr 1 · apply Finset.sum_congr rfl intro S hS rw [observableProjection_plain gs f H S (Finset.mem_filter.mp hS).2] · apply Finset.sum_congr rfl intro pr hpr obtain ⟨hp,hr,hpr⟩ := (mem_defectTypes gs pr).mp hpr congr 1 simpa only [mul_assoc] using defect_pairing_projection gs hgs hcover f G H hf hG pr.1 pr.2 hp hr hpr noncomputable def extendChainFun (gs : List (Γ × Γ)) (H : ChainIndex gs → ℝ) (S : Set Γ) : ℝ := if h : ChainState gs S then H ⟨S,h⟩ else 0 omit sectionInstance61 sectionInstance62 in lemma extendChainFun_apply [Fintype Γ] [DecidableEq Γ] (gs : List (Γ × Γ)) (H : ChainIndex gs → ℝ) (S : ChainIndex gs) : extendChainFun gs H S.val = H S := by simp [extendChainFun,S.property] end ProjectionBridge section ObservableMSE open scoped BigOperators Classical variable {Γ : Type*} [Fintype Γ] [DecidableEq Γ] lemma metropolisChain_inner (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hne : gs ≠ []) (hcover : pairSupport gs = Set.univ) (w : (Γ × Γ) → (Γ × Γ) → ℝ) (f G H : Set Γ → ℝ) (hw : ∀ p r,0 < w p r) (hf : ∀ S,0 < f S) : (metropolisChain gs hgs hne hcover w f hw hf).inner (fun S => G S.val) (fun S => H S.val) = (∑ S ∈ chainStates gs,chainWeight gs w f S*G S*H S)/chainTotal gs w f := by change (∑ S : ChainIndex gs,(chainWeight gs w f S.val/chainTotal gs w f)*G S.val*H S.val) = _ simp_rw [div_mul_eq_mul_div] rw [← Finset.sum_div,chain_sum_subtype] lemma metropolisChain_mean (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hne : gs ≠ []) (hcover : pairSupport gs = Set.univ) (w : (Γ × Γ) → (Γ × Γ) → ℝ) (f G : Set Γ → ℝ) (hw : ∀ p r,0 < w p r) (hf : ∀ S,0 < f S) : (metropolisChain gs hgs hne hcover w f hw hf).mean (fun S => G S.val) = chainMean gs w f G := by change (∑ S : ChainIndex gs,(chainWeight gs w f S.val/chainTotal gs w f)*G S.val) = _ simp_rw [div_mul_eq_mul_div] unfold chainMean rw [← Finset.sum_div,chain_sum_subtype] lemma metropolisChain_variance (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hne : gs ≠ []) (hcover : pairSupport gs = Set.univ) (w : (Γ × Γ) → (Γ × Γ) → ℝ) (f G : Set Γ → ℝ) (hw : ∀ p r,0 < w p r) (hf : ∀ S,0 < f S) : (metropolisChain gs hgs hne hcover w f hw hf).variance (fun S => G S.val) = chainVariance gs w f G := by rw [FiniteChain.variance,metropolisChain_mean] rw [metropolisChain_inner gs hgs hne hcover w f (fun S => G S-chainMean gs w f G) (fun S => G S-chainMean gs w f G) hw hf] unfold chainVariance congr 1 apply Finset.sum_congr rfl intro S _ ring theorem metropolisChain_dual (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hne : gs ≠ []) (hcover : pairSupport gs = Set.univ) (w : (Γ × Γ) → (Γ × Γ) → ℝ) (f G : Set Γ → ℝ) (hw : ∀ p r,0 < w p r) (hf : ∀ S,0 < f S) (hsig : HasSlotSignature f) (hG : ClassObservable gs G) (hlower : ∀ p ∈ gs, ∀ r ∈ gs, p ≠ r → slotTotal gs f ∅/(4*slotDefect gs f ∅ p r) ≤ w p r) (hupper : ∀ p ∈ gs, ∀ r ∈ gs, p ≠ r → w p r ≤ 4*slotTotal gs f ∅/slotDefect gs f ∅ p r) (H : ChainIndex gs → ℝ) : let C := metropolisChain gs hgs hne hcover w f hw hf let g := fun S : ChainIndex gs => G S.val-chainMean gs w f G (C.inner g H)^2 ≤ (2000*(gs.length:ℝ)^6)*C.inner g g*C.energy H := by let C := metropolisChain gs hgs hne hcover w f hw hf let a := chainMean gs w f G let g := fun S : ChainIndex gs => G S.val-a let H' := extendChainFun gs H let QH := fun S : ChainIndex gs => observableProjection gs f H' S.val have hext : (fun S : ChainIndex gs => H' S.val) = H := by funext S exact extendChainFun_apply gs H S have hmean : C.mean g = 0 := by have hm := metropolisChain_mean gs hgs hne hcover w f G hw hf change C.mean (fun S => G S.val-a) = 0 change C.mean (fun S : ChainIndex gs => G S.val) = a at hm rw [← hm] exact C.centered_mean _ have hpair : C.inner g H = C.inner g QH := by rw [← hext] change C.inner (fun S => (G S.val-a)) (fun S => H' S.val) = C.inner (fun S => (G S.val-a)) (fun S => observableProjection gs f H' S.val) dsimp only [C] rw [metropolisChain_inner gs hgs hne hcover w f (fun S => G S-a) H' hw hf, metropolisChain_inner gs hgs hne hcover w f (fun S => G S-a) (observableProjection gs f H') hw hf] exact congrArg (fun t => t/chainTotal gs w f) (chain_pairing_projection gs hgs hcover w f (fun S => G S-a) H' hf (hG.sub_const a)) have hbound : C.variance QH ≤ (2000*(gs.length:ℝ)^6)*C.energy H := by change (metropolisChain gs hgs hne hcover w f hw hf).variance (fun S => observableProjection gs f H' S.val) ≤ _ rw [metropolisChain_variance] have hb := observable_poincare gs hgs hne hcover w hw f H' hf hsig hlower hupper rw [← metropolisChain_energy gs hgs hne hcover w f H' hw hf,hext] at hb exact hb change (C.inner g H)^2 ≤ (2000*(gs.length:ℝ)^6)*C.inner g g*C.energy H rw [hpair,← C.inner_center_right g QH hmean (C.mean QH)] calc _ ≤ C.inner g g*C.variance QH := C.inner_cauchy _ _ _ ≤ C.inner g g*((2000*(gs.length:ℝ)^6)*C.energy H) := mul_le_mul_of_nonneg_left hbound (C.inner_nonneg g) _ = _ := by ring theorem metropolisChain_timeAverage (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hne : gs ≠ []) (hcover : pairSupport gs = Set.univ) (w : (Γ × Γ) → (Γ × Γ) → ℝ) (f G : Set Γ → ℝ) (hw : ∀ p r,0 < w p r) (hf : ∀ S,0 < f S) (hsig : HasSlotSignature f) (hG : ClassObservable gs G) (hlower : ∀ p ∈ gs, ∀ r ∈ gs, p ≠ r → slotTotal gs f ∅/(4*slotDefect gs f ∅ p r) ≤ w p r) (hupper : ∀ p ∈ gs, ∀ r ∈ gs, p ≠ r → w p r ≤ 4*slotTotal gs f ∅/slotDefect gs f ∅ p r) (U : ℝ) (hU : 0 ≤ U) (ν : ChainIndex gs → ℝ) (hwarm : ∀ S,ν S ≤ U*chainWeight gs w f S.val/chainTotal gs w f) (N : ℕ) (hN : 0 < N) : let C := metropolisChain gs hgs hne hcover w f hw hf let g := fun S : ChainIndex gs => G S.val-chainMean gs w f G (∑ S,ν S*C.squareMoment g N S)/(N:ℝ)^2 ≤ 2*U*(2000*(gs.length:ℝ)^6)*chainVariance gs w f G/N := by let C := metropolisChain gs hgs hne hcover w f hw hf let g := fun S : ChainIndex gs => G S.val-chainMean gs w f G have hi : C.inner g g = chainVariance gs w f G := by rw [← metropolisChain_variance gs hgs hne hcover w f G hw hf] unfold FiniteChain.variance rw [metropolisChain_mean] have h := C.warm_squareMoment_bound g (2000*(gs.length:ℝ)^6) U (by positivity) hU (metropolisChain_dual gs hgs hne hcover w f G hw hf hsig hG hlower hupper) ν (by intro S; simpa only [C,metropolisChain,FiniteChain.ofMoves,mul_div_assoc] using hwarm S) N hN rw [hi] at h exact h end ObservableMSE structure KilledKernel (B : Type*) [Fintype B] where Q : B → B → ℝ r : ℝ nonnegative : ∀ x y,0 ≤ Q x y rnonneg : 0 ≤ r rlt : r < 1 rowbound : ∀ x,∑ y,Q x y ≤ r namespace KilledKernel open scoped BigOperators Classical open Filter variable {B : Type*} [Fintype B] (Q : KilledKernel B) noncomputable def apply (f : B → ℝ) (x : B) : ℝ := ∑ y,Q.Q x y*f y noncomputable def iterate (k : ℕ) (f : B → ℝ) : B → ℝ := Nat.iterate Q.apply k f @[simp] lemma iterate_zero (f : B → ℝ) : Q.iterate 0 f = f := rfl lemma iterate_succ (k : ℕ) (f : B → ℝ) : Q.iterate (k+1) f = Q.apply (Q.iterate k f) := Function.iterate_succ_apply' Q.apply k f lemma iterate_succ' (k : ℕ) (f : B → ℝ) : Q.iterate (k+1) f = Q.iterate k (Q.apply f) := Function.iterate_succ_apply Q.apply k f lemma apply_add (f g : B → ℝ) : Q.apply (fun x => f x+g x) = fun x => Q.apply f x+Q.apply g x := by funext x simp [apply,mul_add,Finset.sum_add_distrib] lemma apply_sub (f g : B → ℝ) : Q.apply (fun x => f x-g x) = fun x => Q.apply f x-Q.apply g x := by funext x simp [apply,mul_sub,Finset.sum_sub_distrib] lemma apply_sum {J : Type*} (s : Finset J) (f : J → B → ℝ) : Q.apply (fun x => ∑ j ∈ s,f j x) = fun x => ∑ j ∈ s,Q.apply (f j) x := by funext x simp only [apply,Finset.mul_sum] exact Finset.sum_comm lemma apply_mul (a : ℝ) (f : B → ℝ) : Q.apply (fun x => a*f x) = fun x => a*Q.apply f x := by funext x simp only [apply,Finset.mul_sum] apply Finset.sum_congr rfl intro y _ ring lemma apply_nonneg (f : B → ℝ) (hf : ∀ x,0 ≤ f x) (x : B) : 0 ≤ Q.apply f x := Finset.sum_nonneg (fun y _ => mul_nonneg (Q.nonnegative x y) (hf y)) lemma iterate_nonneg (k : ℕ) (f : B → ℝ) (hf : ∀ x,0 ≤ f x) (x : B) : 0 ≤ Q.iterate k f x := by induction k generalizing x with | zero => exact hf x | succ k ih => rw [Q.iterate_succ] exact Q.apply_nonneg _ ih x lemma apply_abs_bound (f : B → ℝ) (M : ℝ) (hM : 0 ≤ M) (hf : ∀ x,|f x| ≤ M) (x : B) : |Q.apply f x| ≤ Q.r*M := by calc _ ≤ ∑ y,|Q.Q x y*f y| := Finset.abs_sum_le_sum_abs _ _ _ = ∑ y,Q.Q x y*|f y| := by simp_rw [abs_mul,abs_of_nonneg (Q.nonnegative x _) ] _ ≤ ∑ y,Q.Q x y*M := Finset.sum_le_sum (fun y _ => mul_le_mul_of_nonneg_left (hf y) (Q.nonnegative x y)) _ = (∑ y,Q.Q x y)*M := (Finset.sum_mul _ _ _).symm _ ≤ Q.r*M := mul_le_mul_of_nonneg_right (Q.rowbound x) hM lemma iterate_abs_bound (k : ℕ) (f : B → ℝ) (M : ℝ) (hM : 0 ≤ M) (hf : ∀ x,|f x| ≤ M) (x : B) : |Q.iterate k f x| ≤ Q.r^k*M := by induction k generalizing x with | zero => simpa using hf x | succ k ih => rw [Q.iterate_succ,pow_succ'] simpa only [mul_assoc] using Q.apply_abs_bound (Q.iterate k f) (Q.r^k*M) (mul_nonneg (pow_nonneg Q.rnonneg _) hM) ih x lemma summable_iterate (f : B → ℝ) (x : B) : Summable (fun k => Q.iterate k f x) := by let M := ∑ y,|f y| have hM : 0 ≤ M := Finset.sum_nonneg (fun y _ => abs_nonneg _) have hf : ∀ y,|f y| ≤ M := fun y => Finset.single_le_sum (f := fun z => |f z|) (fun z _ => abs_nonneg _) (Finset.mem_univ y) exact (Summable.of_nonneg_of_le (fun k => abs_nonneg _) (fun k => Q.iterate_abs_bound k f M hM hf x) ((summable_geometric_of_lt_one Q.rnonneg Q.rlt).mul_right M)).of_abs lemma iterate_tendsto_zero (f : B → ℝ) (x : B) : Tendsto (fun k => Q.iterate k f x) atTop (nhds 0) := by let M := ∑ y,|f y| have hM : 0 ≤ M := Finset.sum_nonneg (fun y _ => abs_nonneg _) have hf : ∀ y,|f y| ≤ M := fun y => Finset.single_le_sum (f := fun z => |f z|) (fun z _ => abs_nonneg _) (Finset.mem_univ y) have ht : Tendsto (fun k => Q.r^k*M) atTop (nhds 0) := by simpa using (tendsto_pow_atTop_nhds_zero_of_lt_one Q.rnonneg Q.rlt).mul_const M exact (tendsto_zero_iff_abs_tendsto_zero _).mpr (squeeze_zero (fun k => abs_nonneg _) (fun k => Q.iterate_abs_bound k f M hM hf x) ht) noncomputable def green (f : B → ℝ) (x : B) : ℝ := ∑' k,Q.iterate k f x lemma green_nonneg (f : B → ℝ) (hf : ∀ x,0 ≤ f x) (x : B) : 0 ≤ Q.green f x := tsum_nonneg (fun k => Q.iterate_nonneg k f hf x) lemma green_firstStep (f : B → ℝ) (x : B) : Q.green f x = f x+Q.apply (Q.green f) x := by unfold green rw [(Q.summable_iterate f x).tsum_eq_zero_add] simp only [Q.iterate_zero,Q.iterate_succ,apply] congr 1 rw [Summable.tsum_finsetSum (fun y (_ : y ∈ Finset.univ) => (Q.summable_iterate f y).mul_left (Q.Q x y))] simp_rw [tsum_mul_left] lemma iterate_sub (k : ℕ) (f g : B → ℝ) : Q.iterate k (fun x => f x-g x) = fun x => Q.iterate k f x-Q.iterate k g x := by induction k with | zero => rfl | succ k ih => rw [Q.iterate_succ,ih,Q.apply_sub,← Q.iterate_succ,← Q.iterate_succ] lemma iterate_sum {J : Type*} (s : Finset J) (f : J → B → ℝ) (k : ℕ) : Q.iterate k (fun x => ∑ j ∈ s,f j x) = fun x => ∑ j ∈ s,Q.iterate k (f j) x := by induction k with | zero => rfl | succ k ih => rw [Q.iterate_succ,ih,Q.apply_sum]; simp_rw [← Q.iterate_succ] lemma iterate_mul (a : ℝ) (f : B → ℝ) (k : ℕ) : Q.iterate k (fun x => a*f x) = fun x => a*Q.iterate k f x := by induction k with | zero => rfl | succ k ih => rw [Q.iterate_succ,ih,Q.apply_mul,← Q.iterate_succ] lemma green_sum {J : Type*} (s : Finset J) (f : J → B → ℝ) (x : B) : Q.green (fun x => ∑ j ∈ s,f j x) x = ∑ j ∈ s,Q.green (f j) x := by unfold green simp_rw [Q.iterate_sum] exact Summable.tsum_finsetSum (fun j _ => Q.summable_iterate (f j) x) lemma green_mul (a : ℝ) (f : B → ℝ) (x : B) : Q.green (fun x => a*f x) x = a*Q.green f x := by unfold green simp_rw [Q.iterate_mul] exact tsum_mul_left lemma iterate_residual_sum (f : B → ℝ) (N : ℕ) (x : B) : (∑ k ∈ Finset.range N,Q.iterate k (fun y => f y-Q.apply f y) x) = f x-Q.iterate N f x := by induction N with | zero => simp | succ N ih => rw [Finset.sum_range_succ,ih,Q.iterate_sub,← Q.iterate_succ'] simp only ring lemma green_residual (f : B → ℝ) (x : B) : Q.green (fun y => f y-Q.apply f y) x = f x := by have hs := (Q.summable_iterate (fun y => f y-Q.apply f y) x).tendsto_sum_tsum_nat simp_rw [Q.iterate_residual_sum] at hs have ht : Tendsto (fun N => f x-Q.iterate N f x) atTop (nhds (f x)) := by simpa using tendsto_const_nhds.sub (Q.iterate_tendsto_zero f x) exact tendsto_nhds_unique hs ht end KilledKernel namespace FiniteChain section open scoped BigOperators Classical variable {X : Type*} [sectionInstance66 : Fintype X] (C : FiniteChain X) (A : X → Prop) abbrev Inside := {x : X // A x} abbrev Outside := {x : X // ¬ A x} noncomputable def mergeFun (h : Inside A → ℝ) (b : Outside A → ℝ) (x : X) : ℝ := if hx : A x then h ⟨x,hx⟩ else b ⟨x,hx⟩ omit sectionInstance66 in @[simp] lemma mergeFun_inside [Fintype X] (h : Inside A → ℝ) (b : Outside A → ℝ) (x : Inside A) : mergeFun A h b x.val = h x := by simp [mergeFun,x.property] omit sectionInstance66 in @[simp] lemma mergeFun_outside [Fintype X] (h : Inside A → ℝ) (b : Outside A → ℝ) (x : Outside A) : mergeFun A h b x.val = b x := by simp [mergeFun,x.property] variable (Q : KilledKernel (Outside A)) (hQ : ∀ x y : Outside A,Q.Q x y = C.P x.val y.val) noncomputable def hitKernel (x : Outside A) (y : Inside A) : ℝ := Q.green (fun z => C.P z.val y.val) x lemma hitKernel_nonneg (x : Outside A) (y : Inside A) : 0 ≤ C.hitKernel A Q x y := Q.green_nonneg _ (fun z => C.nonnegative z.val y.val) x include hQ in lemma exitRow (x : Outside A) : (∑ y : Inside A,C.P x.val y.val) = 1-Q.apply (fun _ => 1) x := by have hh := Fintype.sum_subtype_add_sum_subtype A (fun y => C.P x.val y) rw [C.stochastic] at hh have he : Q.apply (fun _ => 1) x = ∑ y : Outside A,C.P x.val y.val := by simp [KilledKernel.apply,hQ] rw [he] linarith include hQ in lemma hitKernel_row (x : Outside A) : ∑ y : Inside A,C.hitKernel A Q x y = 1 := by unfold hitKernel rw [← Q.green_sum Finset.univ] have he : (fun z : Outside A => ∑ y : Inside A,C.P z.val y.val) = fun z => 1-Q.apply (fun _ => 1) z := by funext z exact C.exitRow A Q hQ z rw [he,Q.green_residual] include hQ in lemma hitKernel_firstStep (x : Outside A) (y : Inside A) : C.hitKernel A Q x y = C.P x.val y.val+∑ z : Outside A,C.P x.val z.val*C.hitKernel A Q z y := by unfold hitKernel rw [Q.green_firstStep] simp only [KilledKernel.apply,hQ] noncomputable def traceMatrix (x y : Inside A) : ℝ := C.P x.val y.val+∑ z : Outside A,C.P x.val z.val*C.hitKernel A Q z y noncomputable def traceApply (h : Inside A → ℝ) (x : Inside A) : ℝ := ∑ y,C.traceMatrix A Q x y*h y lemma traceMatrix_nonneg (x y : Inside A) : 0 ≤ C.traceMatrix A Q x y := add_nonneg (C.nonnegative _ _) (Finset.sum_nonneg (fun z _ => mul_nonneg (C.nonnegative _ _) (C.hitKernel_nonneg A Q z y))) lemma traceMatrix_lazy (x : Inside A) : 1/2 ≤ C.traceMatrix A Q x x := by exact (C.lazy x.val).trans (le_add_of_nonneg_right (Finset.sum_nonneg (fun z _ => mul_nonneg (C.nonnegative _ _) (C.hitKernel_nonneg A Q z x)))) include hQ in lemma traceMatrix_stochastic (x : Inside A) : ∑ y,C.traceMatrix A Q x y = 1 := by unfold traceMatrix rw [Finset.sum_add_distrib,Finset.sum_comm] simp_rw [← Finset.mul_sum,C.hitKernel_row A Q hQ,mul_one] rw [Fintype.sum_subtype_add_sum_subtype A,C.stochastic] noncomputable def offExtension (h : Inside A → ℝ) (x : Outside A) : ℝ := ∑ y : Inside A,C.hitKernel A Q x y*h y noncomputable def harmonicExtension (h : Inside A → ℝ) : X → ℝ := mergeFun A h (C.offExtension A Q h) @[simp] lemma harmonicExtension_inside (h : Inside A → ℝ) (x : Inside A) : C.harmonicExtension A Q h x.val = h x := mergeFun_inside _ _ _ _ @[simp] lemma harmonicExtension_outside (h : Inside A → ℝ) (x : Outside A) : C.harmonicExtension A Q h x.val = C.offExtension A Q h x := mergeFun_outside _ _ _ _ include hQ in lemma offExtension_firstStep (h : Inside A → ℝ) (x : Outside A) : C.offExtension A Q h x = (∑ y : Inside A,C.P x.val y.val*h y)+ ∑ z : Outside A,C.P x.val z.val*C.offExtension A Q h z := by unfold offExtension calc _ = ∑ y : Inside A,(C.P x.val y.val+∑ z : Outside A,C.P x.val z.val*C.hitKernel A Q z y)*h y := by apply Finset.sum_congr rfl intro y _ rw [C.hitKernel_firstStep A Q hQ] _ = _ := ?_ simp only [add_mul,Finset.sum_mul,Finset.sum_add_distrib] congr 1 rw [Finset.sum_comm] apply Finset.sum_congr rfl intro z _ simp_rw [mul_assoc,← Finset.mul_sum] include hQ in lemma harmonicExtension_harmonic (h : Inside A → ℝ) (x : Outside A) : C.apply (C.harmonicExtension A Q h) x.val = C.harmonicExtension A Q h x.val := by unfold apply rw [← Fintype.sum_subtype_add_sum_subtype A] simp only [C.harmonicExtension_inside,C.harmonicExtension_outside] exact (C.offExtension_firstStep A Q hQ h x).symm lemma apply_harmonicExtension_inside (h : Inside A → ℝ) (x : Inside A) : C.apply (C.harmonicExtension A Q h) x.val = C.traceApply A Q h x := by unfold apply rw [← Fintype.sum_subtype_add_sum_subtype A] simp only [C.harmonicExtension_inside,C.harmonicExtension_outside] unfold traceApply traceMatrix offExtension simp_rw [add_mul,Finset.sum_mul,Finset.sum_add_distrib,Finset.mul_sum] congr 1 rw [Finset.sum_comm] apply Finset.sum_congr rfl intro y _ apply Finset.sum_congr rfl intro z _ ring include hQ in lemma harmonic_inner_residual (h g : Inside A → ℝ) : C.inner (C.harmonicExtension A Q h) (fun x => C.harmonicExtension A Q g x-C.apply (C.harmonicExtension A Q g) x) = ∑ x : Inside A,C.π x.val*h x*(g x-C.traceApply A Q g x) := by unfold inner rw [← Fintype.sum_subtype_add_sum_subtype A] simp only [C.harmonicExtension_inside,C.apply_harmonicExtension_inside, C.harmonicExtension_harmonic A Q hQ,sub_self,mul_zero,Finset.sum_const_zero,add_zero] end section open scoped BigOperators Classical variable {X : Type*} [Fintype X] (C : FiniteChain X) (A : X → Prop) variable (Q : KilledKernel (Outside A)) (hQ : ∀ x y : Outside A,Q.Q x y = C.P x.val y.val) lemma residual_symmetric (f g : X → ℝ) : C.inner f (fun x => g x-C.apply g x) = C.inner g (fun x => f x-C.apply f x) := by rw [C.inner_sub_right,C.inner_sub_right,C.apply_selfAdjoint,C.inner_symm f g, C.inner_symm (C.apply f) g] include hQ in lemma traceMatrix_reversible (x y : Inside A) : C.π x.val*C.traceMatrix A Q x y = C.π y.val*C.traceMatrix A Q y x := by by_cases hxy : x = y · subst y; rfl have h := C.residual_symmetric (C.harmonicExtension A Q (fun z => if z=x then 1 else 0)) (C.harmonicExtension A Q (fun z => if z=y then 1 else 0)) rw [C.harmonic_inner_residual A Q hQ,C.harmonic_inner_residual A Q hQ] at h simp [traceApply,hxy,Ne.symm hxy] at h linarith noncomputable def insideMass : ℝ := ∑ x : Inside A,C.π x.val lemma insideMass_pos [Nonempty (Inside A)] : 0 < C.insideMass A := by apply Finset.sum_pos · intro x _; exact C.positive _ · exact Finset.univ_nonempty noncomputable def traceChain [Nonempty (Inside A)] : FiniteChain (Inside A) where P := C.traceMatrix A Q π := fun x => C.π x.val/C.insideMass A positive := fun x => div_pos (C.positive _) (C.insideMass_pos A) normalized := by rw [← Finset.sum_div]; exact div_self (C.insideMass_pos A).ne' nonnegative := C.traceMatrix_nonneg A Q stochastic := C.traceMatrix_stochastic A Q hQ reversible := by intro x y rw [div_mul_eq_mul_div,div_mul_eq_mul_div,C.traceMatrix_reversible A Q hQ] lazy := C.traceMatrix_lazy A Q lemma traceChain_energy [Nonempty (Inside A)] (h : Inside A → ℝ) : C.energy (C.harmonicExtension A Q h) = C.insideMass A*(C.traceChain A Q hQ).energy h := by rw [energy,C.harmonic_inner_residual A Q hQ] change _ = C.insideMass A*(∑ x : Inside A, (C.π x.val/C.insideMass A)*h x*(h x-C.traceApply A Q h x)) rw [Finset.mul_sum] apply Finset.sum_congr rfl intro x _ field_simp [(C.insideMass_pos A).ne'] lemma mean_apply (f : X → ℝ) : C.mean (C.apply f) = C.mean f := by unfold mean apply simp_rw [Finset.mul_sum] rw [Finset.sum_comm] simp_rw [← mul_assoc,← Finset.sum_mul,C.stationary] lemma mean_residual (f : X → ℝ) : C.mean (fun x => f x-C.apply f x) = 0 := by unfold mean simp_rw [mul_sub,Finset.sum_sub_distrib] change C.mean f-C.mean (C.apply f) = 0 rw [C.mean_apply,sub_self] noncomputable def duration (x : Outside A) : ℝ := Q.green (fun _ => 1) x noncomputable def returnCost (x : Inside A) : ℝ := 1+∑ y : Outside A,C.P x.val y.val*duration A Q y lemma duration_nonneg (x : Outside A) : 0 ≤ duration A Q x := Q.green_nonneg _ (by intro; norm_num) x lemma returnCost_nonneg (x : Inside A) : 0 ≤ C.returnCost A Q x := add_nonneg (by norm_num) (Finset.sum_nonneg (fun y _ => mul_nonneg (C.nonnegative _ _) (duration_nonneg A Q y))) include hQ in lemma expected_returnCost : (∑ x : Inside A,C.π x.val*C.returnCost A Q x) = 1 := by let l : X → ℝ := mergeFun A (fun _ => 0) (duration A Q) have hi (x : Inside A) : l x.val = 0 := by simp [l] have ho (x : Outside A) : l x.val = duration A Q x := by simp [l] have hai (x : Inside A) : C.apply l x.val = ∑ y : Outside A,C.P x.val y.val*duration A Q y := by unfold apply rw [← Fintype.sum_subtype_add_sum_subtype A] simp only [hi,ho,mul_zero,Finset.sum_const_zero,zero_add] have hao (x : Outside A) : C.apply l x.val = Q.apply (duration A Q) x := by unfold apply rw [← Fintype.sum_subtype_add_sum_subtype A] simp only [hi,ho,mul_zero,Finset.sum_const_zero,zero_add,KilledKernel.apply,hQ] have hr (x : Outside A) : l x.val-C.apply l x.val = 1 := by rw [ho,hao] have hg := Q.green_firstStep (fun _ => (1:ℝ)) x change duration A Q x = 1+Q.apply (duration A Q) x at hg linarith have hm := C.mean_residual l unfold mean at hm rw [← Fintype.sum_subtype_add_sum_subtype A] at hm simp only [hi,hai,hr,zero_sub,mul_neg,Finset.sum_neg_distrib,mul_one] at hm have hmass := Fintype.sum_subtype_add_sum_subtype A C.π rw [C.normalized] at hmass unfold returnCost simp only [mul_add,mul_one,Finset.sum_add_distrib] linarith lemma traceChain_returnCost [Nonempty (Inside A)] : (C.traceChain A Q hQ).mean (C.returnCost A Q) = 1/C.insideMass A := by change (∑ x : Inside A,(C.π x.val/C.insideMass A)*C.returnCost A Q x) = _ simp_rw [div_mul_eq_mul_div] rw [← Finset.sum_div,C.expected_returnCost A Q hQ] lemma warm_returnCost [Nonempty (Inside A)] (ν : Inside A → ℝ) (U : ℝ) (hν : ∀ x,ν x ≤ U*(C.traceChain A Q hQ).π x) : (∑ x,ν x*C.returnCost A Q x) ≤ U/C.insideMass A := by calc _ ≤ ∑ x,U*(C.traceChain A Q hQ).π x*C.returnCost A Q x := Finset.sum_le_sum (fun x _ => mul_le_mul_of_nonneg_right (hν x) (C.returnCost_nonneg A Q x)) _ = U*(C.traceChain A Q hQ).mean (C.returnCost A Q) := by simp [mean,Finset.mul_sum,mul_assoc] _ = _ := by rw [C.traceChain_returnCost A Q hQ]; ring end section open scoped BigOperators Classical variable {X : Type*} [Fintype X] (C : FiniteChain X) (A : X → Prop) variable (hExit : ∀ x : Outside A,∃ y : Inside A,0 < C.P x.val y.val) noncomputable def exitProbability (x : Outside A) : ℝ := ∑ y : Inside A,C.P x.val y.val lemma exitProbability_nonneg (x : Outside A) : 0 ≤ C.exitProbability A x := Finset.sum_nonneg (fun y _ => C.nonnegative x.val y.val) include hExit in lemma exitProbability_pos (x : Outside A) : 0 < C.exitProbability A x := by obtain ⟨y,hy⟩ := hExit x exact hy.trans_le (Finset.single_le_sum (fun z _ => C.nonnegative _ _) (Finset.mem_univ y)) lemma exitProbability_le_one (x : Outside A) : C.exitProbability A x ≤ 1 := by have h := Fintype.sum_subtype_add_sum_subtype A (fun y => C.P x.val y) rw [C.stochastic] at h have hn : 0 ≤ ∑ y : Outside A,C.P x.val y.val := Finset.sum_nonneg (fun y _ => C.nonnegative _ _) change (∑ y : Inside A,C.P x.val y.val) ≤ 1 linarith noncomputable def killedChain : KilledKernel (Outside A) where Q := fun x y => C.P x.val y.val r := 1-∏ x : Outside A,C.exitProbability A x nonnegative := fun x y => C.nonnegative _ _ rnonneg := sub_nonneg.mpr (Finset.prod_le_one₀ (fun x _ => C.exitProbability_nonneg A x) (fun x _ => C.exitProbability_le_one A x)) rlt := by have h : 0 < ∏ x : Outside A,C.exitProbability A x := Finset.prod_pos (fun x _ => C.exitProbability_pos A hExit x) linarith rowbound := by intro x have hprod : (∏ z : Outside A,C.exitProbability A z) ≤ C.exitProbability A x := by have h := Finset.prod_le_prod_of_subset_of_le_one₀ (Finset.singleton_subset_iff.mpr (Finset.mem_univ x)) (fun z (_ : z ∈ Finset.univ) => C.exitProbability_nonneg A z) (fun z _ _ => C.exitProbability_le_one A z) simpa only [Finset.prod_singleton] using h have hs := Fintype.sum_subtype_add_sum_subtype A (fun y => C.P x.val y) rw [C.stochastic] at hs change (∑ y : Inside A,C.P x.val y.val)+(∑ y : Outside A,C.P x.val y.val) = 1 at hs unfold exitProbability at hprod ⊢ linarith end open scoped Classical BigOperators variable {X : Type*} [Fintype X] (C : FiniteChain X) lemma apply_cauchy (f g : X → ℝ) : (C.inner f (C.apply g))^2 ≤ C.inner f (C.apply f)*C.inner g (C.apply g) := by let B : LinearMap.BilinForm ℝ (X → ℝ) := Matrix.toBilin' (fun x y => C.π x*C.P x y) have he (u v : X → ℝ) : B u v = C.inner u (C.apply v) := by simp only [B,inner,apply,Finset.mul_sum] apply Finset.sum_congr rfl intro x _ apply Finset.sum_congr rfl intro y _ change v y*(u x*(C.π x*C.P x y))=C.π x*u x*(C.P x y*v y) ring have hs : LinearMap.IsSymm B := by constructor intro u v simp only [he,RingHom.id_apply] rw [C.apply_selfAdjoint,C.inner_symm] simpa only [he] using B.apply_sq_le_of_symm (fun u => by rw [he]; exact C.apply_positive u) hs f g lemma inner_sub_left (f g h : X → ℝ) : C.inner (fun x => f x-g x) h = C.inner f h-C.inner g h := by rw [C.inner_symm,C.inner_sub_right,C.inner_symm h f,C.inner_symm h g] lemma apply_sub (f g : X → ℝ) : C.apply (fun x => f x-g x) = fun x => C.apply f x-C.apply g x := by funext x simp [apply,mul_sub,Finset.sum_sub_distrib] lemma mean_const (a : ℝ) : C.mean (fun _ => a) = a := by simp [mean,← Finset.sum_mul,C.normalized] lemma mean_sub (f g : X → ℝ) : C.mean (fun x => f x-g x) = C.mean f-C.mean g := by simp [mean,mul_sub,Finset.sum_sub_distrib] lemma variance_eq_inner (f : X → ℝ) (hf : C.mean f = 0) : C.variance f = C.inner f f := by simp [variance,hf] lemma apply_contraction (r : ℝ) (hr : 0 ≤ r) (hgap : ∀ f : X → ℝ,C.mean f = 0 → C.inner f (C.apply f) ≤ r*C.inner f f) (f : X → ℝ) (hf : C.mean f = 0) : C.inner (C.apply f) (C.apply f) ≤ r^2*C.inner f f := by have hg : C.mean (C.apply f) = 0 := by rw [C.mean_apply,hf] have hcs := C.apply_cauchy (C.apply f) f have h₁ := hgap f hf have h₂ := hgap (C.apply f) hg have hp₁ := C.apply_positive f have hp₂ := C.apply_positive (C.apply f) have hn := C.inner_nonneg (C.apply f) have hm := C.inner_nonneg f have hb := mul_le_mul h₂ h₁ hp₁ (mul_nonneg hr hn) by_cases hz : C.inner (C.apply f) (C.apply f) = 0 · rw [hz]; positivity · have hpos : 0 < C.inner (C.apply f) (C.apply f) := lt_of_le_of_ne hn (Ne.symm hz) nlinarith lemma iterate_mean (k : ℕ) (f : X → ℝ) : C.mean (C.iterate k f) = C.mean f := by induction k with | zero => rfl | succ k ih => rw [C.iterate_succ,C.mean_apply,ih] lemma iterate_contraction (r : ℝ) (hr : 0 ≤ r) (hgap : ∀ f : X → ℝ,C.mean f = 0 → C.inner f (C.apply f) ≤ r*C.inner f f) (k : ℕ) (f : X → ℝ) (hf : C.mean f = 0) : C.inner (C.iterate k f) (C.iterate k f) ≤ r^(2*k)*C.inner f f := by induction k with | zero => simp | succ k ih => rw [C.iterate_succ] calc _ ≤ r^2*C.inner (C.iterate k f) (C.iterate k f) := C.apply_contraction r hr hgap _ (by rw [C.iterate_mean,hf]) _ ≤ r^2*(r^(2*k)*C.inner f f) := mul_le_mul_of_nonneg_left ih (sq_nonneg r) _ = _ := by rw [show 2*(k+1)=2+2*k by omega,pow_add]; ring noncomputable def pointDensity (x : X) (y : X) : ℝ := if y=x then 1/C.π x else 0 noncomputable def centeredPoint (x : X) (y : X) : ℝ := C.pointDensity x y-1 lemma pointDensity_mean (x : X) : C.mean (C.pointDensity x) = 1 := by simp [mean,pointDensity,(C.positive x).ne'] lemma centeredPoint_mean (x : X) : C.mean (C.centeredPoint x) = 0 := by change C.mean (fun z => C.pointDensity x z-1) = 0 rw [C.mean_sub,C.pointDensity_mean,C.mean_const,sub_self] lemma pointDensity_inner (x : X) (f : X → ℝ) : C.inner (C.pointDensity x) f = f x := by simp [inner,pointDensity,(C.positive x).ne'] lemma centeredPoint_norm (x : X) : C.inner (C.centeredPoint x) (C.centeredPoint x) ≤ 1/C.π x := by unfold centeredPoint rw [C.inner_sub_left,C.inner_sub_right,C.inner_sub_right,C.pointDensity_inner, C.pointDensity_inner,C.inner_symm (fun _ => 1),C.pointDensity_inner] have h₁ : C.inner (fun _ => 1) (fun _ => 1) = 1 := by simp [inner,C.normalized] rw [h₁] simp only [pointDensity,ite_true] linarith lemma iterate_const (k : ℕ) (a : ℝ) : C.iterate k (fun _ => a) = fun _ => a := by induction k with | zero => rfl | succ k ih => rw [C.iterate_succ,ih,C.apply_const] lemma iterate_sub (k : ℕ) (f g : X → ℝ) : C.iterate k (fun x => f x-g x) = fun x => C.iterate k f x-C.iterate k g x := by induction k with | zero => rfl | succ k ih => rw [C.iterate_succ,ih,C.apply_sub,C.iterate_succ,C.iterate_succ] lemma point_mixing_squared (r : ℝ) (hr : 0 ≤ r) (hgap : ∀ f : X → ℝ,C.mean f = 0 → C.inner f (C.apply f) ≤ r*C.inner f f) (k : ℕ) (x y : X) : (C.iterate k (C.pointDensity y) x-1)^2 ≤ r^(2*k)/(C.π x*C.π y) := by have he : C.inner (C.centeredPoint x) (C.iterate k (C.centeredPoint y)) = C.iterate k (C.pointDensity y) x-1 := by change C.inner (fun z => C.pointDensity x z-1) (C.iterate k (C.centeredPoint y)) = _ rw [C.inner_sub_left,C.pointDensity_inner] have hm : C.inner (fun _ => 1) (C.iterate k (C.centeredPoint y)) = 0 := by have hz := C.iterate_mean k (C.centeredPoint y) rw [C.centeredPoint_mean] at hz simpa only [inner,mean,mul_one] using hz rw [hm,sub_zero] change C.iterate k (fun z => C.pointDensity y z-1) x = _ rw [C.iterate_sub,C.iterate_const] have hcs := C.inner_cauchy (C.centeredPoint x) (C.iterate k (C.centeredPoint y)) rw [he] at hcs have hcon := C.iterate_contraction r hr hgap k (C.centeredPoint y) (C.centeredPoint_mean y) have hny := C.centeredPoint_norm y have hnx := C.centeredPoint_norm x have hb := mul_le_mul hnx (hcon.trans (mul_le_mul_of_nonneg_left hny (pow_nonneg hr _))) (C.inner_nonneg _) (div_nonneg (by norm_num) (C.positive x).le) calc _ ≤ _ := hcs.trans hb _ = _ := by field_simp lemma variance_formula (f : X → ℝ) : C.variance f = C.inner f f-(C.mean f)^2 := by rw [variance,C.inner_sub_left,C.inner_sub_right,C.inner_sub_right] have h₁ : C.inner f (fun _ => C.mean f) = (C.mean f)^2 := by unfold inner rw [← Finset.sum_mul] change C.mean f*C.mean f = (C.mean f)^2 ring have h₂ : C.inner (fun _ => C.mean f) (fun _ => C.mean f) = (C.mean f)^2 := by simp only [inner,← Finset.sum_mul,C.normalized,one_mul,pow_two] rw [h₁,C.inner_symm (fun _ => C.mean f) f,h₁,h₂] ring lemma poincare_rayleigh (K : ℝ) (hK : 0 < K) (hp : ∀ f : X → ℝ,C.variance f ≤ K*C.energy f) (f : X → ℝ) (hf : C.mean f = 0) : C.inner f (C.apply f) ≤ (1-1/K)*C.inner f f := by have h := hp f rw [C.variance_eq_inner f hf,energy,C.inner_sub_right] at h apply (mul_le_mul_iff_right₀ hK).mp field_simp nlinarith lemma point_mixing (r m : ℝ) (hr : 0 ≤ r) (hm : 0 < m) (hπ : ∀ x,m ≤ C.π x) (hgap : ∀ f : X → ℝ,C.mean f = 0 → C.inner f (C.apply f) ≤ r*C.inner f f) (k : ℕ) (x y : X) : |C.iterate k (C.pointDensity y) x-1| ≤ r^k/m := by have hs := C.point_mixing_squared r hr hgap k x y have hd : m^2 ≤ C.π x*C.π y := by simpa only [pow_two] using mul_le_mul (hπ x) (hπ y) hm.le (C.positive x).le have hb : r^(2*k)/(C.π x*C.π y) ≤ (r^k/m)^2 := by calc _ ≤ r^(2*k)/m^2 := div_le_div_of_nonneg_left (pow_nonneg hr _) (sq_pos_of_pos hm) hd _ = _ := by rw [mul_comm 2 k,pow_mul,div_pow] have ha : (|C.iterate k (C.pointDensity y) x-1|)^2 ≤ (r^k/m)^2 := by rw [sq_abs] exact hs.trans hb exact (sq_le_sq₀ (abs_nonneg _) (div_nonneg (pow_nonneg hr _) hm.le)).mp ha lemma point_mixing_exp (K m : ℝ) (hK : 1 ≤ K) (hm : 0 < m) (hπ : ∀ x,m ≤ C.π x) (hp : ∀ f : X → ℝ,C.variance f ≤ K*C.energy f) (k : ℕ) (x y : X) : |C.iterate k (C.pointDensity y) x-1| ≤ Real.exp (-(k:ℝ)/K)/m := by have hKp : 0 < K := lt_of_lt_of_le (by norm_num) hK have hr : 0 ≤ 1-1/K := sub_nonneg.mpr ((div_le_one hKp).mpr hK) have hpow : (1-1/K)^k ≤ Real.exp (-(k:ℝ)/K) := by have hle : 1-1/K ≤ Real.exp (-1/K) := by have hh := Real.add_one_le_exp (-1/K) convert hh using 1 ; ring calc _ ≤ (Real.exp (-1/K))^k := pow_le_pow_left₀ hr hle k _ = Real.exp ((k:ℝ)*(-1/K)) := (Real.exp_nat_mul _ _).symm _ = _ := by congr 1; ring exact (C.point_mixing _ m hr hm hπ (C.poincare_rayleigh K hKp hp) k x y).trans (div_le_div_of_nonneg_right hpow hm.le) end FiniteChain section TraceGeometry open scoped Classical BigOperators variable {Γ : Type*} [Fintype Γ] [sectionInstance71 : DecidableEq Γ] lemma SlotsFresh.cross_ne {gs : List (Γ × Γ)} {A : Set Γ} (hgs : SlotsFresh gs A) {p r : Γ × Γ} (hp : p ∈ gs) (hr : r ∈ gs) (hpr : p ≠ r) {x y : Γ} (hx : x=p.1 ∨ x=p.2) (hy : y=r.1 ∨ y=r.2) : x ≠ y := by intro hxy have := hgs.pair_contains_unique hp hr hx (hxy ▸ hy) exact hpr this lemma DefectState.plain_neighbor {gs : List (Γ × Γ)} (hgs : SlotsFresh gs ∅) {p r : Γ × Γ} {S : Set Γ} (hS : DefectState gs p r S) : ∃ T,PlainState gs T ∧ ExchangeAdjacent S T := by obtain ⟨hp,hr,hpr,he,hf,ht⟩ := hS let T := insert p.1 (S\{r.1}) have hpne : p.1 ≠ p.2 := ((SlotsFresh.perm (List.perm_cons_erase hp) ∅).mp hgs).1 have hrne : r.1 ≠ r.2 := ((SlotsFresh.perm (List.perm_cons_erase hr) ∅).mp hgs).1 have hpr11 : p.1 ≠ r.1 := hgs.cross_ne hp hr hpr (Or.inl rfl) (Or.inl rfl) have hpr21 : p.2 ≠ r.1 := hgs.cross_ne hp hr hpr (Or.inr rfl) (Or.inl rfl) have hpr12 : p.1 ≠ r.2 := hgs.cross_ne hp hr hpr (Or.inl rfl) (Or.inr rfl) refine ⟨T,?_,?_⟩ · intro t htm by_cases htp : t=p · subst t simp [PairSingle,T,hpne.symm,he.1,he.2] by_cases htr : t=r · subst t simp [PairSingle,T,hpr11.symm,hpr12.symm,hrne.symm,hf.2] have h₁ : t.1 ≠ p.1 := hgs.cross_ne htm hp htp (Or.inl rfl) (Or.inl rfl) have h₂ : t.2 ≠ p.1 := hgs.cross_ne htm hp htp (Or.inr rfl) (Or.inl rfl) have h₃ : t.1 ≠ r.1 := hgs.cross_ne htm hr htr (Or.inl rfl) (Or.inl rfl) have h₄ : t.2 ≠ r.1 := hgs.cross_ne htm hr htr (Or.inr rfl) (Or.inl rfl) simpa only [PairSingle,T,Set.mem_insert_iff,Set.mem_sdiff,Set.mem_singleton_iff, h₁,h₂,h₃,h₄,false_or,not_false_eq_true,and_true] using ht t htm htp htr · refine ⟨S\{r.1},r.1,p.1,hpr11.symm,by simp,?_,?_,rfl⟩ · exact fun h => he.1 h.1 · ext x simp only [Set.mem_insert_iff,Set.mem_sdiff,Set.mem_singleton_iff] constructor · intro hx by_cases h : x=r.1 · exact Or.inl h · exact Or.inr ⟨hx,h⟩ · rintro (rfl|⟨hx,_⟩) · exact hf.1 · exact hx abbrev PlainIndex (gs : List (Γ × Γ)) := FiniteChain.Inside (fun S : ChainIndex gs => PlainState gs S.val) omit sectionInstance71 in lemma plainIndex_sum [DecidableEq Γ] (gs : List (Γ × Γ)) (g : Set Γ → ℝ) : (∑ S : PlainIndex gs,g S.val.val) = ∑ S ∈ Finset.univ.filter (PlainState gs),g S := by let e : PlainIndex gs ≃ {S : Set Γ // PlainState gs S} := { toFun := fun S => ⟨S.val.val,S.property⟩ invFun := fun S => ⟨⟨S.val,Or.inl S.property⟩,S.property⟩ left_inv := by intro; rfl right_inv := by intro; rfl } calc _ = ∑ S : {S : Set Γ // PlainState gs S},g S.val := Fintype.sum_equiv e _ _ (by intro S; rfl) _ = _ := (Finset.sum_subtype _ (by intro S; simp) g).symm lemma plainIndex_nonempty (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hcover : pairSupport gs = Set.univ) : Nonempty (PlainIndex gs) := by have hz := slotTotal_pos gs (fun _ => (1:ℝ)) (by intro; norm_num) ∅ hgs rw [slotTotal_eq_plain_sum gs hgs hcover,← plainIndex_sum] at hz by_contra h have : IsEmpty (PlainIndex gs) := not_nonempty_iff.mp h simp at hz lemma metropolis_plain_exit (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hne : gs ≠ []) (hcover : pairSupport gs = Set.univ) (w : (Γ × Γ) → (Γ × Γ) → ℝ) (f : Set Γ → ℝ) (hw : ∀ p r,0 < w p r) (hf : ∀ S,0 < f S) (S : FiniteChain.Outside (fun S : ChainIndex gs => PlainState gs S.val)) : ∃ T : PlainIndex gs,0 < (metropolisChain gs hgs hne hcover w f hw hf).P S.val T.val := by obtain ⟨p,r,hS⟩ := S.val.property.resolve_left S.property obtain ⟨T,hT,hST⟩ := hS.plain_neighbor hgs let t : PlainIndex gs := ⟨⟨T,Or.inl hT⟩,hT⟩ refine ⟨t,?_⟩ have hneST : S.val ≠ t.val := by intro h; exact hST.ne (congrArg Subtype.val h) change 0 < metropolisMove gs w f S.val t.val+if S.val=t.val then _ else _ rw [ite_eq_right hneST,add_zero] unfold metropolisMove rw [ite_eq_left hST] have hn : (0:ℝ) < gs.length := by exact_mod_cast List.length_pos_iff.mpr hne exact div_pos (lt_min (chainWeight_pos gs w f hw hf _) (chainWeight_pos gs w f hw hf _)) (mul_pos (mul_pos (by norm_num) (sq_pos_of_pos hn)) (chainWeight_pos gs w f hw hf _)) end TraceGeometry section TracePoincare open scoped Classical BigOperators variable {Γ : Type*} [Fintype Γ] [DecidableEq Γ] variable (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hne : gs ≠ []) (hcover : pairSupport gs = Set.univ) (w : (Γ × Γ) → (Γ × Γ) → ℝ) (f : Set Γ → ℝ) (hw : ∀ p r,0 < w p r) (hf : ∀ S,0 < f S) abbrev plainPredicate (gs : List (Γ × Γ)) (S : ChainIndex gs) := PlainState gs S.val noncomputable def metropolisKilled : KilledKernel (FiniteChain.Outside (plainPredicate gs)) := (metropolisChain gs hgs hne hcover w f hw hf).killedChain (plainPredicate gs) (metropolis_plain_exit gs hgs hne hcover w f hw hf) noncomputable def metropolisTrace : FiniteChain (PlainIndex gs) := by letI := plainIndex_nonempty gs hgs hcover exact (metropolisChain gs hgs hne hcover w f hw hf).traceChain (plainPredicate gs) (metropolisKilled gs hgs hne hcover w f hw hf) (by intro _ _; rfl) lemma metropolis_insideMass : (metropolisChain gs hgs hne hcover w f hw hf).insideMass (plainPredicate gs) = slotTotal gs f ∅/chainTotal gs w f := by change (∑ S : PlainIndex gs,chainWeight gs w f S.val.val/chainTotal gs w f) = _ have he (S : PlainIndex gs) : chainWeight gs w f S.val.val = f S.val.val := by rw [chainWeight,chainMultiplier_plain gs w S.val.val S.property,one_mul] simp_rw [he] rw [← Finset.sum_div,plainIndex_sum,slotTotal_eq_plain_sum gs hgs hcover] lemma metropolisTrace_pi (S : PlainIndex gs) : (metropolisTrace gs hgs hne hcover w f hw hf).π S = f S.val.val/slotTotal gs f ∅ := by change (chainWeight gs w f S.val.val/chainTotal gs w f)/ (metropolisChain gs hgs hne hcover w f hw hf).insideMass (plainPredicate gs) = _ rw [metropolis_insideMass gs hgs hne hcover w f hw hf,chainWeight, chainMultiplier_plain gs w S.val.val S.property,one_mul] field_simp [(chainTotal_pos gs hgs hcover w f hf hw).ne'] lemma metropolisTrace_variance (H : Set Γ → ℝ) : (metropolisTrace gs hgs hne hcover w f hw hf).variance (fun S => H S.val.val) = slotVariance gs f H ∅/slotTotal gs f ∅ := by rw [FiniteChain.variance_formula] unfold FiniteChain.inner FiniteChain.mean simp_rw [metropolisTrace_pi,div_mul_eq_mul_div,← Finset.sum_div] rw [plainIndex_sum gs (fun S => f S*H S*H S),plainIndex_sum gs (fun S => f S*H S), slotVariance_eq_plain_variance gs hgs hcover,slotTotal_eq_plain_sum gs hgs hcover] have he : (∑ S with PlainState gs S,f S*H S*H S) = ∑ S with PlainState gs S,f S*(H S)^2 := by apply Finset.sum_congr rfl; intro S _; ring rw [he] have hz := (slotTotal_pos gs f hf ∅ hgs).ne' rw [slotTotal_eq_plain_sum gs hgs hcover] at hz field_simp theorem metropolisTrace_poincare (hsig : HasSlotSignature f) (hgood : ∀ p ∈ gs,∀ r ∈ gs,p ≠ r → slotTotal gs f ∅/(4*slotDefect gs f ∅ p r) ≤ w p r) (h : PlainIndex gs → ℝ) : (metropolisTrace gs hgs hne hcover w f hw hf).variance h ≤ 18*(gs.length:ℝ)^4*(metropolisTrace gs hgs hne hcover w f hw hf).energy h := by let := plainIndex_nonempty gs hgs hcover let C := metropolisChain gs hgs hne hcover w f hw hf let Q := metropolisKilled gs hgs hne hcover w f hw hf let H := C.harmonicExtension (plainPredicate gs) Q h let F := extendChainFun gs H have hF (S : ChainIndex gs) : F S.val = H S := extendChainFun_apply gs H S have hh (S : PlainIndex gs) : F S.val.val = h S := by rw [hF]; exact C.harmonicExtension_inside (plainPredicate gs) Q h S have hvar := metropolisTrace_variance gs hgs hne hcover w f hw hf F have hefun : (fun S : PlainIndex gs => F S.val.val) = h := funext hh rw [hefun] at hvar have hv := transversal_variance_bound gs f F w hf hsig hgs hw hgood have hz := slotTotal_pos gs f hf ∅ hgs have hΛ := chainTotal_pos gs hgs hcover w f hf hw have hn : (1:ℝ) ≤ gs.length := by exact_mod_cast List.length_pos_iff.mpr hne have henergy : restrictedEnergy (chainEdges gs) (chainConductance gs w f) F ∅ ∅ = (2*(gs.length:ℝ)^2*slotTotal gs f ∅)*(metropolisTrace gs hgs hne hcover w f hw hf).energy h := by have hc := metropolisChain_energy gs hgs hne hcover w f F hw hf have hfFn : (fun S : ChainIndex gs => F S.val) = H := funext hF rw [hfFn] at hc change C.energy (C.harmonicExtension (plainPredicate gs) Q h) = _ at hc rw [C.traceChain_energy (plainPredicate gs) Q (by intro _ _; rfl)] at hc change C.insideMass (plainPredicate gs)*(metropolisTrace gs hgs hne hcover w f hw hf).energy h = _ at hc rw [metropolis_insideMass gs hgs hne hcover w f hw hf] at hc unfold chainDirichlet at hc field_simp at hc nlinarith rw [henergy] at hv rw [hvar] have hE := (metropolisTrace gs hgs hne hcover w f hw hf).energy_nonneg h apply (div_le_iff₀ hz).mpr have hconst : (gs.length:ℝ)*(1+8*(gs.length:ℝ))*(2*(gs.length:ℝ)^2) ≤ 18*(gs.length:ℝ)^4 := by nlinarith [sq_nonneg ((gs.length:ℝ)-1),sq_nonneg (gs.length:ℝ)] have hb := mul_le_mul_of_nonneg_right hconst (mul_nonneg hz.le hE) nlinarith end TracePoincare namespace KilledKernel open scoped BigOperators Classical variable {B : Type*} [Fintype B] (Q : KilledKernel B) lemma apply_mono {f g : B → ℝ} (h : ∀ x,f x ≤ g x) (x : B) : Q.apply f x ≤ Q.apply g x := Finset.sum_le_sum (fun y _ => mul_le_mul_of_nonneg_left (h y) (Q.nonnegative x y)) lemma iterate_mono {f g : B → ℝ} (h : ∀ x,f x ≤ g x) (k : ℕ) (x : B) : Q.iterate k f x ≤ Q.iterate k g x := by induction k generalizing x with | zero => exact h x | succ k ih => rw [Q.iterate_succ,Q.iterate_succ]; exact Q.apply_mono ih x lemma survival_antitone (x : B) : Antitone (fun k => Q.iterate k (fun _ => 1) x) := by apply antitone_nat_of_succ_le intro k rw [Q.iterate_succ'] apply Q.iterate_mono intro y simpa only [apply,mul_one] using (Q.rowbound y).trans Q.rlt.le lemma duration_tail (N : ℕ) (x : B) : (N:ℝ)*Q.iterate N (fun _ => 1) x ≤ Q.green (fun _ => 1) x := by calc _ = ∑ k ∈ Finset.range N,Q.iterate N (fun _ => 1) x := by simp _ ≤ ∑ k ∈ Finset.range N,Q.iterate k (fun _ => 1) x := Finset.sum_le_sum (fun k hk => Q.survival_antitone x (Finset.mem_range.mp hk).le) _ ≤ _ := (Q.summable_iterate (fun _ => 1) x).sum_le_tsum (Finset.range N) (fun k _ => Q.iterate_nonneg k _ (by intro; norm_num) x) noncomputable def partialGreen (N : ℕ) (f : B → ℝ) (x : B) : ℝ := ∑ k ∈ Finset.range N,Q.iterate k f x lemma partialGreen_nonneg (N : ℕ) (f : B → ℝ) (hf : ∀ x,0 ≤ f x) (x : B) : 0 ≤ Q.partialGreen N f x := Finset.sum_nonneg (fun k _ => Q.iterate_nonneg k f hf x) lemma partialGreen_le (N : ℕ) (f : B → ℝ) (hf : ∀ x,0 ≤ f x) (x : B) : Q.partialGreen N f x ≤ Q.green f x := (Q.summable_iterate f x).sum_le_tsum (Finset.range N) (fun k _ => Q.iterate_nonneg k f hf x) lemma partialGreen_sum {J : Type*} (s : Finset J) (f : J → B → ℝ) (N : ℕ) (x : B) : Q.partialGreen N (fun y => ∑ j ∈ s,f j y) x = ∑ j ∈ s,Q.partialGreen N (f j) x := by unfold partialGreen simp_rw [Q.iterate_sum] exact Finset.sum_comm end KilledKernel namespace FiniteChain open scoped BigOperators Classical variable {X : Type*} [Fintype X] (C : FiniteChain X) (A : X → Prop) (Q : KilledKernel (Outside A)) (hQ : ∀ x y,Q.Q x y=C.P x.val y.val) noncomputable def cappedTrace (N : ℕ) (x y : Inside A) : ℝ := C.P x.val y.val + ∑ z : Outside A,C.P x.val z.val* Q.partialGreen N (fun t => C.P t.val y.val) z lemma cappedTrace_nonneg (N : ℕ) (x y : Inside A) : 0 ≤ C.cappedTrace A Q N x y := by apply add_nonneg (C.nonnegative _ _) exact Finset.sum_nonneg (fun z _ => mul_nonneg (C.nonnegative _ _) (Q.partialGreen_nonneg N _ (fun t => C.nonnegative _ _) z)) lemma cappedTrace_le (N : ℕ) (x y : Inside A) : C.cappedTrace A Q N x y ≤ C.traceMatrix A Q x y := by unfold cappedTrace traceMatrix apply add_le_add_right apply Finset.sum_le_sum intro z _ exact mul_le_mul_of_nonneg_left (Q.partialGreen_le N _ (fun t => C.nonnegative _ _) z) (C.nonnegative _ _) include hQ in lemma cappedTrace_mass (N : ℕ) (x : Inside A) : ∑ y,C.cappedTrace A Q N x y = 1-∑ z : Outside A,C.P x.val z.val*Q.iterate N (fun _ => 1) z := by unfold cappedTrace rw [Finset.sum_add_distrib,Finset.sum_comm] simp_rw [← Finset.mul_sum,← Q.partialGreen_sum] have he : (fun t : Outside A => ∑ y : Inside A,C.P t.val y.val) = fun t => 1-Q.apply (fun _ => 1) t := by funext t exact C.exitRow A Q hQ t rw [he] simp_rw [KilledKernel.partialGreen,Q.iterate_residual_sum,mul_sub,mul_one,Finset.sum_sub_distrib] have hs := Fintype.sum_subtype_add_sum_subtype A (fun y => C.P x.val y) rw [C.stochastic] at hs linarith include hQ in lemma cappedTrace_loss (N : ℕ) (x : Inside A) : (N:ℝ)*(1-∑ y,C.cappedTrace A Q N x y) ≤ C.returnCost A Q x := by rw [C.cappedTrace_mass A Q hQ] simp only [sub_sub_cancel] calc _ = ∑ z : Outside A,C.P x.val z.val*((N:ℝ)*Q.iterate N (fun _ => 1) z) := by rw [Finset.mul_sum]; apply Finset.sum_congr rfl; intro z _; ring _ ≤ ∑ z : Outside A,C.P x.val z.val*duration A Q z := Finset.sum_le_sum (fun z _ => mul_le_mul_of_nonneg_left (Q.duration_tail N z) (C.nonnegative _ _)) _ ≤ _ := by unfold returnCost; linarith include hQ in lemma cappedTrace_substochastic (N : ℕ) (x : Inside A) : ∑ y,C.cappedTrace A Q N x y ≤ 1 := by calc _ ≤ ∑ y,C.traceMatrix A Q x y := Finset.sum_le_sum (fun y _ => C.cappedTrace_le A Q N x y) _ = 1 := C.traceMatrix_stochastic A Q hQ x lemma cappedTrace_warm_loss [Nonempty (Inside A)] (N : ℕ) (U : ℝ) (ν : Inside A → ℝ) (hν : ∀ x,0 ≤ ν x) (hwarm : ∀ x,ν x ≤ U*(C.traceChain A Q hQ).π x) : (N:ℝ)*(∑ x,ν x*(1-∑ y,C.cappedTrace A Q N x y)) ≤ U/C.insideMass A := by calc _ = ∑ x,ν x*((N:ℝ)*(1-∑ y,C.cappedTrace A Q N x y)) := by rw [Finset.mul_sum]; apply Finset.sum_congr rfl; intro x _; ring _ ≤ ∑ x,ν x*C.returnCost A Q x := Finset.sum_le_sum (fun x _ => mul_le_mul_of_nonneg_left (C.cappedTrace_loss A Q hQ N x) (hν x)) _ ≤ _ := C.warm_returnCost A Q hQ ν U hwarm end FiniteChain structure FiniteKernel (X Y : Type*) [Fintype Y] where P : X → Y → ℝ nonnegative : ∀ x y,0 ≤ P x y substochastic : ∀ x,∑ y,P x y ≤ 1 namespace FiniteKernel open scoped BigOperators Classical variable {X Y Z : Type*} [Fintype X] [Fintype Y] [Fintype Z] noncomputable def identity : FiniteKernel X X where P x y := if x=y then 1 else 0 nonnegative := by intros; split_ifs <;> norm_num substochastic := by intro x; simp noncomputable def comp (K : FiniteKernel X Y) (L : FiniteKernel Y Z) : FiniteKernel X Z where P x z := ∑ y,K.P x y*L.P y z nonnegative := by intros; exact Finset.sum_nonneg (fun y _ => mul_nonneg (K.nonnegative _ _) (L.nonnegative _ _)) substochastic := by intro x rw [Finset.sum_comm] simp_rw [← Finset.mul_sum] calc _ ≤ ∑ y,K.P x y*1 := Finset.sum_le_sum (fun y _ => mul_le_mul_of_nonneg_left (L.substochastic y) (K.nonnegative x y)) _ ≤ 1 := by simp only [mul_one]; exact K.substochastic x noncomputable def push (K : FiniteKernel X Y) (ν : X → ℝ) (y : Y) := ∑ x,ν x*K.P x y lemma push_nonneg (K : FiniteKernel X Y) (ν : X → ℝ) (hν : ∀ x,0 ≤ ν x) (y : Y) : 0 ≤ K.push ν y := Finset.sum_nonneg (fun x _ => mul_nonneg (hν x) (K.nonnegative x y)) lemma push_mono (K : FiniteKernel X Y) {ν ν' : X → ℝ} (h : ∀ x,ν x ≤ ν' x) (y : Y) : K.push ν y ≤ K.push ν' y := Finset.sum_le_sum (fun x _ => mul_le_mul_of_nonneg_right (h x) (K.nonnegative x y)) lemma push_comp (K : FiniteKernel X Y) (L : FiniteKernel Y Z) (ν : X → ℝ) : (K.comp L).push ν = L.push (K.push ν) := by funext z simp only [push,comp,Finset.mul_sum,Finset.sum_mul,mul_assoc] exact Finset.sum_comm lemma push_identity (ν : X → ℝ) : (identity : FiniteKernel X X).push ν = ν := by funext x; simp [push,identity] lemma push_mass (K : FiniteKernel X Y) (ν : X → ℝ) : ∑ y,K.push ν y = ∑ x,ν x*(∑ y,K.P x y) := by unfold push; rw [Finset.sum_comm]; simp_rw [← Finset.mul_sum] lemma push_mass_le (K : FiniteKernel X Y) (ν : X → ℝ) (hν : ∀ x,0 ≤ ν x) : ∑ y,K.push ν y ≤ ∑ x,ν x := by rw [K.push_mass] exact Finset.sum_le_sum (fun x _ => by simpa using mul_le_mul_of_nonneg_left (K.substochastic x) (hν x)) noncomputable def power (K : FiniteKernel X X) : ℕ → FiniteKernel X X | 0 => identity | n+1 => (K.power n).comp K lemma power_push_succ (K : FiniteKernel X X) (n : ℕ) (ν : X → ℝ) : (K.power (n+1)).push ν = K.push ((K.power n).push ν) := (K.power n).push_comp K ν lemma push_domination (K L : FiniteKernel X Y) (hKL : ∀ x y,K.P x y ≤ L.P x y) (ν : X → ℝ) (hν : ∀ x,0 ≤ ν x) (y : Y) : K.push ν y ≤ L.push ν y := Finset.sum_le_sum (fun x _ => mul_le_mul_of_nonneg_left (hKL x y) (hν x)) lemma power_domination (K L : FiniteKernel X X) (hKL : ∀ x y,K.P x y ≤ L.P x y) (n : ℕ) (ν : X → ℝ) (hν : ∀ x,0 ≤ ν x) (y : X) : (K.power n).push ν y ≤ (L.power n).push ν y := by induction n generalizing y with | zero => exact le_rfl | succ n ih => rw [K.power_push_succ,L.power_push_succ] exact (K.push_mono (fun y => ih y) y).trans (K.push_domination L hKL _ ((L.power n).push_nonneg ν hν) y) lemma one_step_defect (K L : FiniteKernel X Y) (hL : ∀ x,∑ y,L.P x y=1) (a b : X → ℝ) (_ : ∀ x,0 ≤ a x) (hab : ∀ x,a x ≤ b x) : (∑ y,L.push b y)-(∑ y,K.push a y) ≤ (∑ x,b x)-(∑ x,a x)+∑ x,b x*(1-∑ y,K.P x y) := by rw [L.push_mass,K.push_mass] simp_rw [hL,mul_one] have hh : ∑ x,a x*(1-∑ y,K.P x y) ≤ ∑ x,b x*(1-∑ y,K.P x y) := Finset.sum_le_sum (fun x _ => mul_le_mul_of_nonneg_right (hab x) (sub_nonneg.mpr (K.substochastic x))) simp_rw [mul_sub,mul_one,Finset.sum_sub_distrib] at hh ⊢ linarith end FiniteKernel namespace FiniteChain section open scoped BigOperators Classical variable {X : Type*} [Fintype X] (C : FiniteChain X) noncomputable def kernel : FiniteKernel X X where P := C.P nonnegative := C.nonnegative substochastic := fun x => (C.stochastic x).le lemma kernel_stationary : C.kernel.push C.π = C.π := by funext y; exact C.stationary y lemma push_warm (ν : X → ℝ) (U : ℝ) (hν : ∀ x,ν x ≤ U*C.π x) (y : X) : C.kernel.push ν y ≤ U*C.π y := by calc _ ≤ ∑ x,U*C.π x*C.P x y := C.kernel.push_mono hν y _ = U*C.π y := by simp only [mul_assoc,← Finset.mul_sum,C.stationary] lemma power_warm (n : ℕ) (ν : X → ℝ) (U : ℝ) (hν : ∀ x,ν x ≤ U*C.π x) (y : X) : (C.kernel.power n).push ν y ≤ U*C.π y := by induction n generalizing y with | zero => simpa [FiniteKernel.power,FiniteKernel.push_identity] using hν y | succ n ih => rw [FiniteKernel.power_push_succ]; exact C.push_warm _ U (fun y => ih y) y lemma kernel_power_stochastic (n : ℕ) (x : X) : ∑ y,(C.kernel.power n).P x y=1 := by induction n with | zero => simp [FiniteKernel.power,FiniteKernel.identity] | succ n ih => change (∑ y,∑ z,(C.kernel.power n).P x z*C.P z y) = 1 rw [Finset.sum_comm] simp_rw [← Finset.mul_sum,C.stochastic,mul_one] exact ih lemma power_push_mass (n : ℕ) (ν : X → ℝ) : ∑ y,(C.kernel.power n).push ν y = ∑ x,ν x := by rw [FiniteKernel.push_mass] simp_rw [C.kernel_power_stochastic,mul_one] lemma capped_power_mass (K : FiniteKernel X X) (hK : ∀ x y,K.P x y≤C.P x y) (ν : X → ℝ) (hν : ∀ x,0≤ν x) (hnorm : ∑ x,ν x=1) (U e : ℝ) (hwarm : ∀ x,ν x≤U*C.π x) (hloss : ∀ a : X → ℝ,(∀ x,0≤a x) → (∀ x,a x≤U*C.π x) → (∑ x,a x*(1-∑ y,K.P x y))≤e) (T : ℕ) : 1-(∑ x,(K.power T).push ν x)≤(T:ℝ)*e := by have hdom := fun n x => K.power_domination C.kernel hK n ν hν x induction T with | zero => simp [FiniteKernel.power,FiniteKernel.push_identity,hnorm] | succ T ih => have h := K.one_step_defect C.kernel C.stochastic ((K.power T).push ν) ((C.kernel.power T).push ν) ((K.power T).push_nonneg ν hν) (hdom T) have hl := hloss ((C.kernel.power T).push ν) ((C.kernel.power T).push_nonneg ν hν) (C.power_warm T ν U hwarm) have hm := C.power_push_mass T ν have hm' := C.power_push_mass (T+1) ν rw [FiniteKernel.power_push_succ] at hm' rw [FiniteKernel.power_push_succ] simp only [hnorm] at hm hm' rw [hm,hm'] at h push_cast linarith variable (A : X → Prop) (Q : KilledKernel (Outside A)) (hQ : ∀ x y,Q.Q x y=C.P x.val y.val) noncomputable def cappedTraceKernel (N : ℕ) : FiniteKernel (Inside A) (Inside A) where P := C.cappedTrace A Q N nonnegative := C.cappedTrace_nonneg A Q N substochastic := C.cappedTrace_substochastic A Q hQ N lemma cappedTrace_power_mass [Nonempty (Inside A)] (N T : ℕ) (hN : 0 exact h _ | succ N ih => apply Finset.sum_le_sum intro y _ exact mul_le_mul_of_nonneg_left (ih y _ _ (fun l => h _)) (C.nonnegative x y) lemma pathExpectation_finsum {J : Type*} (s : Finset J) (N : ℕ) (x : X) (F : J → List X → ℝ) : C.pathExpectation N x (fun l => ∑ j ∈ s,F j l) = ∑ j ∈ s,C.pathExpectation N x (F j) := by induction s using Finset.induction_on with | empty => simp [C.pathExpectation_const] | @insert j s hj ih => simp [Finset.sum_insert,hj,C.pathExpectation_add,ih] lemma pathExpectation_congr_length (N : ℕ) (x : X) (F G : List X → ℝ) (h : ∀ l,l.length=N+1 → F l=G l) : C.pathExpectation N x F=C.pathExpectation N x G := by induction N generalizing x F G with | zero => exact h [x] rfl | succ N ih => apply Finset.sum_congr rfl intro y _ congr 1 apply ih intro l hl exact h (x::l) (by simp [hl]) omit sectionInstance81 in lemma pathSum_center [Fintype X] (G : X → ℝ) (m : ℝ) (l : List X) : pathSum (fun x => G x-m) l = pathSum G l-(l.length:ℝ)*m := by induction l with | nil => simp [pathSum] | cons x l ih => simp only [pathSum_cons,List.length_cons,Nat.cast_add,Nat.cast_one]; rw [ih]; ring noncomputable def pathProbability (ν : X → ℝ) (N : ℕ) (E : List X → Prop) : ℝ := ∑ x,ν x*C.pathExpectation N x (fun l => if E l then 1 else 0) lemma pathProbability_nonneg (ν : X → ℝ) (hν : ∀ x,0≤ν x) (N : ℕ) (E : List X → Prop) : 0≤C.pathProbability ν N E := Finset.sum_nonneg (fun x _ => mul_nonneg (hν x) (C.pathExpectation_nonneg N x _ (by intro l; split_ifs <;> norm_num))) lemma pathProbability_mono (ν : X → ℝ) (hν : ∀ x,0≤ν x) (N : ℕ) (E F : List X → Prop) (h : ∀ l,E l → F l) : C.pathProbability ν N E≤C.pathProbability ν N F := by apply Finset.sum_le_sum intro x _ apply mul_le_mul_of_nonneg_left _ (hν x) apply C.pathExpectation_mono intro l by_cases he : E l · simp [he,h l he] · simp [he]; split_ifs <;> norm_num lemma pathProbability_union {J : Type*} [Fintype J] (ν : X → ℝ) (hν : ∀ x,0≤ν x) (N : ℕ) (E : J → List X → Prop) : C.pathProbability ν N (fun l => ∃ j,E j l) ≤ ∑ j,C.pathProbability ν N (E j) := by classical have h : ∀ l,(if ∃ j,E j l then (1:ℝ) else 0)≤∑ j,if E j l then 1 else 0 := by intro l by_cases he : ∃ j,E j l · obtain ⟨j,hj⟩ := he rw [ite_eq_left ⟨j,hj⟩] calc (1:ℝ) = (if E j l then 1 else 0) := by simp [hj] _ ≤ ∑ j,if E j l then 1 else 0 := Finset.single_le_sum (f := fun j => if E j l then (1:ℝ) else 0) (fun j _ => by split_ifs <;> norm_num) (Finset.mem_univ j) · simp [show ∀ j,¬E j l from fun j hj => he ⟨j,hj⟩] unfold pathProbability calc _ = ∑ x,ν x*C.pathExpectation N x (fun l => if ∃ j,E j l then 1 else 0) := by apply Finset.sum_congr rfl intro x _ congr 1 apply C.pathExpectation_congr intro l split_ifs <;> rfl _ ≤ ∑ x,ν x*C.pathExpectation N x (fun l => ∑ j,if E j l then 1 else 0) := Finset.sum_le_sum (fun x _ => mul_le_mul_of_nonneg_left (C.pathExpectation_mono N x _ _ h) (hν x)) _ = _ := by simp_rw [C.pathExpectation_finsum,Finset.mul_sum]; exact Finset.sum_comm lemma pathProbability_average_error (ν : X → ℝ) (hν : ∀ x,0≤ν x) (G : X → ℝ) (m t : ℝ) (ht : 0 t < |pathSum G l/(N:ℝ)-m|) ≤ ((∑ x,ν x*C.squareMoment (fun x => G x-m) N x)/(N:ℝ)^2)/t^2 := by have hn : (0:ℝ) mul_le_mul_of_nonneg_left (C.pathExpectation_mono (N-1) x _ _ hpoint) (hν x)) change C.pathProbability ν (N-1) _ ≤ _ at h have he : ∀ x,C.pathExpectation (N-1) x (fun l => (pathSum G l/(N:ℝ)-m)^2/t^2) = C.squareMoment (fun x => G x-m) N x/(N:ℝ)^2/t^2 := by intro x rw [squareMoment,ite_eq_right (Nat.ne_of_gt hN)] have hh : C.pathExpectation (N-1) x (fun l => (pathSum G l/(N:ℝ)-m)^2/t^2) = C.pathExpectation (N-1) x (fun l => (1/(N:ℝ)^2/t^2)*(pathSum (fun x => G x-m) l)^2) := by apply C.pathExpectation_congr_length intro l hl have hl' : l.length=N := by omega rw [pathSum_center,hl'] field_simp rw [hh,C.pathExpectation_mul] ring simp_rw [he] at h simpa only [← mul_div_assoc,← Finset.sum_div] using h end open scoped BigOperators Classical variable {X : Type*} [Fintype X] (C : FiniteChain X) lemma variance_le_one (G : X → ℝ) (hG : ∀ x,0≤G x ∧ G x≤1) : C.variance G≤1 := by rw [C.variance_formula] have h : C.inner G G≤1 := by calc _ ≤ ∑ x,C.π x*1 := Finset.sum_le_sum (fun x _ => by have hx := hG x have hh : G x*G x≤1 := by nlinarith simpa only [mul_assoc] using mul_le_mul_of_nonneg_left hh (C.positive x).le) _ = 1 := by simpa using C.normalized nlinarith [sq_nonneg (C.mean G)] lemma relative_union_bound {J : Type*} [Fintype J] (ν : X → ℝ) (hν : ∀ x,0≤ν x) (G : J → X → ℝ) (m η v : ℝ) (hm : 0 < m) (hη : 0<η) (hv : 0≤v) (hmean : ∀ j,m≤C.mean (G j)) (N : ℕ) (hN : 0 G j x-C.mean (G j)) N x)/(N:ℝ)^2≤v) : C.pathProbability ν (N-1) (fun l => ∃ j,η*C.mean (G j) < |pathSum (G j) l/(N:ℝ)-C.mean (G j)|) ≤ (Fintype.card J:ℝ)*v/(η*m)^2 := by calc _ ≤ ∑ j,C.pathProbability ν (N-1) (fun l => η*C.mean (G j) < |pathSum (G j) l/(N:ℝ)-C.mean (G j)|) := C.pathProbability_union ν hν (N-1) _ _ ≤ ∑ j,v/(η*m)^2 := by apply Finset.sum_le_sum intro j _ have hj : 0 G S.val-C.mean (fun S => G S.val)) N S)/(N:ℝ)^2 ≤ 40000*(gs.length:ℝ)^8/N := by have h := metropolisChain_timeAverage gs hgs hne hcover w f G hw hf hsig hG hlower hupper (10*(gs.length:ℝ)^2) (by positivity) ν hwarm N hN have hv := (metropolisChain gs hgs hne hcover w f hw hf).variance_le_one (fun S => G S.val) (fun S => hbounded S.val S.property) rw [metropolisChain_variance] at hv dsimp only rw [metropolisChain_mean] calc _ ≤ _ := h _ ≤ 2*(10*(gs.length:ℝ)^2)*(2000*(gs.length:ℝ)^6)*1/N := div_le_div_of_nonneg_right (mul_le_mul_of_nonneg_left hv (by positivity)) (by positivity) _ = _ := by ring lemma phase_error_arithmetic (n L J N : ℕ) (hn : 0 f S*g S) ∅/chainTotal gs w f := by unfold chainMean congr 1 simp only [chainWeight,mul_assoc] rw [chain_sum_decomposition,slotTotal_eq_plain_sum gs hgs hcover] have hplain : (∑ S with PlainState gs S,f S*plainObservable gs g S)= ∑ S with PlainState gs S,f S*g S := by apply Finset.sum_congr rfl intro S hS simp [plainObservable,(Finset.mem_filter.mp hS).2] rw [hplain] have hdef : ∀ pr ∈ defectTypes gs,(∑ S with DefectState gs pr.1 pr.2 S,f S*plainObservable gs g S)=0 := by intro pr hpr apply Finset.sum_eq_zero intro S hS simp [plainObservable,((Finset.mem_filter.mp hS).2).not_plain] rw [add_eq_left] apply Finset.sum_eq_zero intro pr hpr rw [hdef pr hpr,mul_zero] lemma defectIndicator_mean (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hcover : pairSupport gs=Set.univ) (w : (Γ × Γ) → (Γ × Γ) → ℝ) (f : Set Γ → ℝ) (p r : Γ × Γ) (hp : p∈gs) (hr : r∈gs) (hpr : p≠r) : chainMean gs w f (defectIndicator gs p r) = w p r*slotDefect gs f ∅ p r/chainTotal gs w f := by unfold chainMean congr 1 simp only [chainWeight,mul_assoc] rw [chain_sum_decomposition,slotDefect_eq_defect_sum gs hgs hcover f p r hp hr hpr] have hplain : (∑ S with PlainState gs S,f S*defectIndicator gs p r S)=0 := by apply Finset.sum_eq_zero intro S hS have hh : ¬DefectState gs p r S := fun h => h.not_plain (Finset.mem_filter.mp hS).2 simp [defectIndicator,hh] rw [hplain,zero_add] rw [Finset.sum_eq_single (p,r)] · congr 1 apply Finset.sum_congr rfl intro S hS simp [defectIndicator,(Finset.mem_filter.mp hS).2] · intro pr hm hne have he : ∀ S,DefectState gs pr.1 pr.2 S → ¬DefectState gs p r S := by intro S hS h exact hne (Prod.ext (hS.unique h).1 (hS.unique h).2) have hz : (∑ S with DefectState gs pr.1 pr.2 S,f S*defectIndicator gs p r S)=0 := by apply Finset.sum_eq_zero intro S hS simp [defectIndicator,he S (Finset.mem_filter.mp hS).2] rw [hz,mul_zero] · intro h exact (h ((mem_defectTypes gs (p,r)).mpr ⟨hp,hr,hpr⟩)).elim lemma plain_mass_lower (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hne : gs≠[]) (hcover : pairSupport gs=Set.univ) (w : (Γ × Γ) → (Γ × Γ) → ℝ) (f : Set Γ → ℝ) (hw : ∀ p r,0 < w p r) (hf : ∀ S,0 < f S) (hupper : ∀ p∈gs,∀ r∈gs,p≠r → w p r ≤ 4*slotTotal gs f ∅/slotDefect gs f ∅ p r) : 1/(5*(gs.length:ℝ)^2) ≤ slotTotal gs f ∅/chainTotal gs w f := by have hz := slotTotal_pos gs f hf ∅ hgs have hΛ := chainTotal_pos gs hgs hcover w f hf hw have hn : (0:ℝ) < gs.length := by exact_mod_cast List.length_pos_iff.mpr hne apply (div_le_div_iff₀ (by positivity) hΛ).mpr simpa only [one_mul,mul_one,mul_comm] using chainTotal_le gs hgs hne hcover w f hf hupper lemma defect_mass_lower (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hne : gs≠[]) (hcover : pairSupport gs=Set.univ) (w : (Γ × Γ) → (Γ × Γ) → ℝ) (f : Set Γ → ℝ) (hw : ∀ p r,0 < w p r) (hf : ∀ S,0 < f S) (hlower : ∀ p∈gs,∀ r∈gs,p≠r → slotTotal gs f ∅/(4*slotDefect gs f ∅ p r) ≤ w p r) (hupper : ∀ p∈gs,∀ r∈gs,p≠r → w p r ≤ 4*slotTotal gs f ∅/slotDefect gs f ∅ p r) (p r : Γ × Γ) (hp : p∈gs) (hr : r∈gs) (hpr : p≠r) : 1/(20*(gs.length:ℝ)^2) ≤ chainMean gs w f (defectIndicator gs p r) := by rw [defectIndicator_mean gs hgs hcover w f p r hp hr hpr] have hc := slotDefect_pos gs f hf ∅ hgs p r hp hr hpr have hΛ := chainTotal_pos gs hgs hcover w f hf hw have hwc : slotTotal gs f ∅/4 ≤ w p r*slotDefect gs f ∅ p r := by have h := (div_le_iff₀ (show 0 < 4*slotDefect gs f ∅ p r by positivity)).mp (hlower p hp r hr hpr) linarith calc _ = (1/(5*(gs.length:ℝ)^2))/4 := by ring _ ≤ (slotTotal gs f ∅/chainTotal gs w f)/4 := div_le_div_of_nonneg_right (plain_mass_lower gs hgs hne hcover w f hw hf hupper) (by norm_num) _ = (slotTotal gs f ∅/4)/chainTotal gs w f := by ring _ ≤ _ := div_le_div_of_nonneg_right hwc hΛ.le lemma chainMean_mono (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hcover : pairSupport gs=Set.univ) (w : (Γ × Γ) → (Γ × Γ) → ℝ) (f G H : Set Γ → ℝ) (hw : ∀ p r,0 < w p r) (hf : ∀ S,0 < f S) (h : ∀ S,ChainState gs S → G S ≤ H S) : chainMean gs w f G ≤ chainMean gs w f H := by apply div_le_div_of_nonneg_right _ (chainTotal_pos gs hgs hcover w f hf hw).le apply Finset.sum_le_sum intro S hS exact mul_le_mul_of_nonneg_left (h S (Finset.mem_filter.mp hS).2) (mul_nonneg (chainMultiplier_pos gs w hw S).le (hf S).le) lemma plainObservable_mass_lower (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hne : gs≠[]) (hcover : pairSupport gs=Set.univ) (w : (Γ × Γ) → (Γ × Γ) → ℝ) (f g : Set Γ → ℝ) (hw : ∀ p r,0 < w p r) (hf : ∀ S,0 < f S) (hg : ∀ S,PlainState gs S → 1/2 ≤ g S) (hupper : ∀ p∈gs,∀ r∈gs,p≠r → w p r ≤ 4*slotTotal gs f ∅/slotDefect gs f ∅ p r) : 1/(20*(gs.length:ℝ)^2) ≤ chainMean gs w f (plainObservable gs g) := by have hm := chainMean_mono gs hgs hcover w f (plainObservable gs (fun _ => 1/2)) (plainObservable gs g) hw hf (by intro S hS; unfold plainObservable; split_ifs with hp; exact hg S hp; rfl) rw [plainObservable_mean gs hgs hcover] at hm have he : slotTotal gs (fun S => f S*(1/2)) ∅ = (1/2)*slotTotal gs f ∅ := by have hfun : (fun S => f S*(1/2)) = fun S => (1/2)*f S := by funext S; ring rw [hfun] exact coeffDerivs_scale _ _ _ _ rw [he] at hm have hl := plain_mass_lower gs hgs hne hcover w f hw hf hupper have hn : (0:ℝ) < gs.length := by exact_mod_cast List.length_pos_iff.mpr hne have hp : 0 ≤ 1/(5*(gs.length:ℝ)^2) := by positivity calc _ ≤ (1/(5*(gs.length:ℝ)^2))/2 := by field_simp; norm_num _ ≤ (slotTotal gs f ∅/chainTotal gs w f)/2 := div_le_div_of_nonneg_right hl (by norm_num) _ ≤ _ := by convert hm using 1 ; ring abbrev PhaseObservables (gs : List (Γ × Γ)) := Option {pr // pr∈defectTypes gs} ⊕ Unit lemma phaseObservables_card (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hne : gs≠[]) : Fintype.card (PhaseObservables gs) ≤ 2*gs.length^2 := by have hn := List.length_pos_iff.mpr hne have hc : (defectTypes gs).card=gs.length*gs.length-gs.length := by rw [defectTypes,Finset.offDiag_card,List.toFinset_card_of_nodup hgs.nodup] simp only [PhaseObservables,Fintype.card_sum,Fintype.card_option,Fintype.card_coe,Fintype.card_unit,hc] have hh : gs.length ≤ gs.length*gs.length := by nlinarith rw [pow_two] omega noncomputable def phaseObservable (gs : List (Γ × Γ)) (g : Set Γ → ℝ) : PhaseObservables gs → Set Γ → ℝ | .inl none => plainObservable gs (fun _ => 1) | .inl (some pr) => defectIndicator gs pr.val.1 pr.val.2 | .inr _ => plainObservable gs g lemma phaseObservable_class (gs : List (Γ × Γ)) (g : Set Γ → ℝ) (j : PhaseObservables gs) : ClassObservable gs (phaseObservable gs g j) := by rcases j with (_ | pr) | u · exact plainObservable_class gs _ · exact defectIndicator_class gs _ _ · exact plainObservable_class gs _ omit sectionInstance85 in lemma phaseObservable_bounded [Fintype Γ] (gs : List (Γ × Γ)) (g : Set Γ → ℝ) (hg : ∀ S,PlainState gs S → 0 ≤ g S ∧ g S ≤ 1) (j : PhaseObservables gs) (S : Set Γ) : 0 ≤ phaseObservable gs g j S ∧ phaseObservable gs g j S ≤ 1 := by rcases j with (_ | pr) | u · simp only [phaseObservable,plainObservable]; split_ifs <;> norm_num · simp only [phaseObservable,defectIndicator]; split_ifs <;> norm_num · simp only [phaseObservable,plainObservable]; split_ifs with h · exact hg S h · norm_num lemma phaseObservable_mean_lower (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hne : gs≠[]) (hcover : pairSupport gs=Set.univ) (w : (Γ × Γ) → (Γ × Γ) → ℝ) (f g : Set Γ → ℝ) (hw : ∀ p r,0 < w p r) (hf : ∀ S,0 < f S) (hg : ∀ S,PlainState gs S → 1/2 ≤ g S) (hlower : ∀ p∈gs,∀ r∈gs,p≠r → slotTotal gs f ∅/(4*slotDefect gs f ∅ p r) ≤ w p r) (hupper : ∀ p∈gs,∀ r∈gs,p≠r → w p r ≤ 4*slotTotal gs f ∅/slotDefect gs f ∅ p r) (j : PhaseObservables gs) : 1/(20*(gs.length:ℝ)^2) ≤ chainMean gs w f (phaseObservable gs g j) := by rcases j with (_ | pr) | u · exact plainObservable_mass_lower gs hgs hne hcover w f _ hw hf (by intros; norm_num) hupper · obtain ⟨hp,hr,hpr⟩ := (mem_defectTypes gs pr.val).mp pr.property exact defect_mass_lower gs hgs hne hcover w f hw hf hlower hupper _ _ hp hr hpr · exact plainObservable_mass_lower gs hgs hne hcover w f g hw hf hg hupper theorem metropolis_phase_failure (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hne : gs≠[]) (hcover : pairSupport gs=Set.univ) (w : (Γ × Γ) → (Γ × Γ) → ℝ) (f g : Set Γ → ℝ) (hw : ∀ p r,0 < w p r) (hf : ∀ S,0 < f S) (hsig : HasSlotSignature f) (hg : ∀ S,PlainState gs S → 1/2 ≤ g S ∧ g S ≤ 1) (hlower : ∀ p∈gs,∀ r∈gs,p≠r → slotTotal gs f ∅/(4*slotDefect gs f ∅ p r) ≤ w p r) (hupper : ∀ p∈gs,∀ r∈gs,p≠r → w p r ≤ 4*slotTotal gs f ∅/slotDefect gs f ∅ p r) (ν : ChainIndex gs → ℝ) (hν : ∀ S,0 ≤ ν S) (hwarm : ∀ S,ν S ≤ (10*(gs.length:ℝ)^2)*chainWeight gs w f S.val/chainTotal gs w f) (L N : ℕ) (η : ℝ) (hη : 0 < η) (hN : (10:ℝ)^10*(L+1)*gs.length^14/η^2 ≤ N) : let C := metropolisChain gs hgs hne hcover w f hw hf C.pathProbability ν (N-1) (fun l => ∃ j : PhaseObservables gs, η*C.mean (fun S => phaseObservable gs g j S.val) < |FiniteChain.pathSum (fun S => phaseObservable gs g j S.val) l/(N:ℝ)- C.mean (fun S => phaseObservable gs g j S.val)|) ≤ 1/(32*(L+1:ℝ)) := by let C := metropolisChain gs hgs hne hcover w f hw hf have hn : 0 < gs.length := List.length_pos_iff.mpr hne have hn' : (0:ℝ) < gs.length := by exact_mod_cast hn have hN' : (0:ℝ) < N := lt_of_lt_of_le (by positivity) hN have hNm : 0 < N := by exact_mod_cast hN' have hμ : ∀ j,1/(20*(gs.length:ℝ)^2) ≤ C.mean (fun S => phaseObservable gs g j S.val) := by intro j rw [metropolisChain_mean] exact phaseObservable_mean_lower gs hgs hne hcover w f g hw hf (fun S hS => (hg S hS).1) hlower hupper j have hb := C.relative_union_bound ν hν (fun j S => phaseObservable gs g j S.val) (1/(20*(gs.length:ℝ)^2)) η (40000*(gs.length:ℝ)^8/N) (by positivity) hη (by positivity) hμ N hNm (fun j => metropolisChain_bounded_MSE gs hgs hne hcover w f (phaseObservable gs g j) hw hf hsig (phaseObservable_class gs g j) (fun S _ => phaseObservable_bounded gs g (fun S hS => ⟨by linarith [(hg S hS).1],(hg S hS).2⟩) j S) hlower hupper ν hwarm N hNm) exact hb.trans (phase_error_arithmetic gs.length L (Fintype.card (PhaseObservables gs)) N hn (phaseObservables_card gs hgs hne) η hη hN) end SamplingObservables open Set section PairedReduction variable {α β : Type*} lemma sum_eRank (M : Matroid α) (N : Matroid β) : (M.sum N).eRank = M.eRank + N.eRank := by obtain ⟨B,hB⟩ := M.exists_isBase obtain ⟨C,hC⟩ := N.exists_isBase have hBC : (M.sum N).IsBase (Sum.inl '' B ∪ Sum.inr '' C) := by rw [Matroid.sum_isBase_iff] simpa [Set.preimage_image_eq _ Sum.inl_injective, Set.preimage_image_eq _ Sum.inr_injective] using And.intro hB hC rw [← hBC.encard_eq_eRank, Set.encard_union_eq, Set.InjOn.encard_image, Set.InjOn.encard_image, hB.encard_eq_eRank, hC.encard_eq_eRank] · exact Sum.inr_injective.injOn · exact Sum.inl_injective.injOn · exact Set.disjoint_image_inl_image_inr def pairedMatroid (M₁ M₂ : Matroid α) : Matroid (α ⊕ α) := M₁.sum M₂✶ def transversal (A : Set α) : Set (α ⊕ α) := Sum.inl '' A ∪ Sum.inr '' Aᶜ @[simp] lemma preimage_inl_transversal (A : Set α) : Sum.inl ⁻¹' transversal A = A := by simp [transversal, Set.preimage_image_eq _ Sum.inl_injective] @[simp] lemma preimage_inr_transversal (A : Set α) : Sum.inr ⁻¹' transversal A = Aᶜ := by simp [transversal, Set.preimage_image_eq _ Sum.inr_injective] lemma transversal_injective : Function.Injective (@transversal α) := by intro A B h have := congrArg (fun S => Sum.inl ⁻¹' S) h simpa using this lemma paired_ground (M₁ M₂ : Matroid α) (h₁ : M₁.E = Set.univ) (h₂ : M₂.E = Set.univ) : (pairedMatroid M₁ M₂).E = Set.univ := by ext x cases x <;> simp [pairedMatroid, h₁, h₂] lemma transversal_isBase_iff (M₁ M₂ : Matroid α) (h₂ : M₂.E = Set.univ) (A : Set α) : (pairedMatroid M₁ M₂).IsBase (transversal A) ↔ M₁.IsBase A ∧ M₂.IsBase A := by simp only [pairedMatroid, Matroid.sum_isBase_iff, preimage_inl_transversal, preimage_inr_transversal, Matroid.dual_isBase_iff', h₂, ← Set.compl_eq_univ_sdiff, compl_compl, Set.subset_univ, and_true] lemma paired_eRank [Fintype α] (M₁ M₂ : Matroid α) (h₂ : M₂.E = Set.univ) (hr : M₁.eRank = M₂.eRank) : (pairedMatroid M₁ M₂).eRank = (Fintype.card α : ℕ∞) := by rw [pairedMatroid, sum_eRank,hr, M₂.eRank_add_eRank_dual,h₂, Set.encard_univ, ENat.card_eq_coe_fintype_card] lemma transversal_encard [Fintype α] (A : Set α) : (transversal A).encard = (Fintype.card α : ℕ∞) := by rw [transversal, Set.encard_union_eq, Set.InjOn.encard_image, Set.InjOn.encard_image, ← Set.encard_union_eq disjoint_compl_right, union_compl_self, Set.encard_univ, ENat.card_eq_coe_fintype_card] · exact Sum.inr_injective.injOn · exact Sum.inl_injective.injOn · exact Set.disjoint_image_inl_image_inr lemma transversal_ncard [Fintype α] (A : Set α) : (transversal A).ncard = Fintype.card α := by exact_mod_cast (Set.coe_ncard_eq_encard (transversal A)).trans (transversal_encard A) end PairedReduction open scoped BigOperators Classical noncomputable def annealRho (n : ℕ) : ℝ := 1 - 1 / (2 * (n : ℝ)) def annealLength (n b : ℕ) : ℕ := 2*n*(n+b) noncomputable def annealTolerance (ε : ℝ) (L : ℕ) : ℝ := ε/(32*((L:ℝ)+1)) lemma annealRho_bounds (n : ℕ) (hn : 0 pow_pos hq _) Finset.univ_nonempty lemma coefficient_step (d : X → ℕ) (n : ℕ) (hn : 0 by have := mul_le_mul_of_nonneg_left (annealStep_bounds n (d x) hn (hd x)).1 (pow_nonneg hq (d x)) linarith) · exact Finset.sum_le_sum (fun x _ => by simpa using mul_le_mul_of_nonneg_left (annealStep_bounds n (d x) hn (hd x)).2 (pow_nonneg hq _)) lemma normalized_drift [Nonempty X] (d : X → ℕ) (n : ℕ) (hn : 0 linarith lemma product_ratios (c : ℕ → ℝ) (hc : ∀ j,0 < c j) (L : ℕ) : (∏ j ∈ Finset.range L,c (j+1)/c j) = c L/c 0 := by induction L with | zero => simp [ne_of_gt (hc 0)] | succ L ih => rw [Finset.prod_range_succ,ih] field_simp [ne_of_gt (hc L),ne_of_gt (hc 0)] lemma relative_product_lower (a : ℕ → ℝ) (L : ℕ) (η : ℝ) (hη0 : 0≤η) (hη1 : η≤1/2) (ha : ∀ j (ha j hj).1) have hap : ∀ j (a j)⁻¹) L η hη0.le (by linarith) hainv rw [Finset.prod_inv_distrib] at hinv have hp : 0 < ∏ j ∈ Finset.range L,a j := Finset.prod_pos (fun j hj => hap j (Finset.mem_range.mp hj)) have hlow : 1-ε/16 ≤ (∏ j ∈ Finset.range L,a j)⁻¹ := by linarith have hmul := (le_div_iff₀ hp).mp (show 1-ε/16 ≤ 1/(∏ j ∈ Finset.range L,a j) by simpa only [one_div] using hlow) constructor · linarith · nlinarith [mul_nonneg (show 0≤ε by linarith) (show 0≤1-ε by linarith)] lemma final_estimate_accuracy (ε Z C Zhat : ℝ) (hε0 : 0<ε) (hε1 : ε<1) (hZ : 0≤Z) (hC : Z≤C ∧ C≤(1+ε/10)*Z) (hhat : (1-ε/4)*C≤Zhat ∧ Zhat≤(1+ε/4)*C) : (1-ε)*Z≤Zhat ∧ Zhat≤(1+ε)*Z := by have hl := mul_le_mul_of_nonneg_left hC.1 (show 0≤1-ε/4 by linarith) have hu := mul_le_mul_of_nonneg_left hC.2 (show 0≤1+ε/4 by linarith) have he : (1+ε/4)*(1+ε/10)≤1+ε := by nlinarith [sq_nonneg ε] have he' := mul_le_mul_of_nonneg_right he hZ constructor <;> nlinarith [mul_nonneg hε0.le hZ] section Contamination variable {X : Type*} [Fintype X] noncomputable def zeroDeficiencyCount (d : X → ℕ) : ℕ := (Finset.univ.filter (fun x => d x=0)).card lemma partition_contamination (d : X → ℕ) (q : ℝ) (hq0 : 0≤q) (hq1 : q≤1) : (zeroDeficiencyCount d:ℝ) ≤ deficiencyPartition d q ∧ deficiencyPartition d q ≤ (zeroDeficiencyCount d:ℝ)+(Fintype.card X:ℝ)*q := by have hcount : (zeroDeficiencyCount d:ℝ) = ∑ x,if d x=0 then (1:ℝ) else 0 := by simp [zeroDeficiencyCount,Finset.sum_boole] rw [hcount] constructor · apply Finset.sum_le_sum intro x _ by_cases h : d x=0 · simp [h] · simp [h,pow_nonneg hq0] · have hs : ∀ x,q^(d x) ≤ (if d x=0 then 1 else 0)+q := by intro x by_cases h : d x=0 · simp [h,hq0] · simp only [h,ite_false,zero_add] have hd : 1≤d x := Nat.one_le_iff_ne_zero.mpr h simpa using pow_le_pow_of_le_one hq0 hq1 hd have hh := Finset.sum_le_sum (s := Finset.univ) (fun x _ => hs x) simpa [deficiencyPartition,Finset.sum_add_distrib] using hh end Contamination namespace FiniteExperiment open scoped BigOperators Classical variable {X : Type*} [sectionInstance89 : Fintype X] noncomputable def expect (K : List X → X → ℝ) : ℕ → List X → (List X → ℝ) → ℝ | 0,h,φ => φ h | t+1,h,φ => ∑ x,K h x*expect K t (h++[x]) φ noncomputable def mass (K : List X → X → ℝ) (t : ℕ) (h : List X) : ℝ := expect K t h (fun _ => 1) lemma expect_nonneg (K : List X → X → ℝ) (hK : ∀ h x,0 ≤ K h x) (φ : List X → ℝ) (hφ : ∀ h,0 ≤ φ h) (t : ℕ) (h : List X) : 0 ≤ expect K t h φ := by induction t generalizing h with | zero => exact hφ h | succ t ih => exact Finset.sum_nonneg (fun x _ => mul_nonneg (hK h x) (ih _)) lemma expect_mono (K : List X → X → ℝ) (hK : ∀ h x,0 ≤ K h x) (φ ψ : List X → ℝ) (hh : ∀ h,φ h ≤ ψ h) (t : ℕ) (h : List X) : expect K t h φ ≤ expect K t h ψ := by induction t generalizing h with | zero => exact hh h | succ t ih => exact Finset.sum_le_sum (fun x _ => mul_le_mul_of_nonneg_left (ih _) (hK h x)) lemma expect_kernel_mono (K P : List X → X → ℝ) (hK : ∀ h x,0 ≤ K h x) (hKP : ∀ h x,K h x ≤ P h x) (φ : List X → ℝ) (hφ : ∀ h,0 ≤ φ h) (t : ℕ) (h : List X) : expect K t h φ ≤ expect P t h φ := by have hP : ∀ h x,0 ≤ P h x := fun h x => (hK h x).trans (hKP h x) induction t generalizing h with | zero => rfl | succ t ih => exact Finset.sum_le_sum (fun x _ => mul_le_mul (hKP h x) (ih _) (expect_nonneg K hK φ hφ t _) (hP h x)) lemma mass_nonneg (K : List X → X → ℝ) (hK : ∀ h x,0 ≤ K h x) (t : ℕ) (h : List X) : 0 ≤ mass K t h := expect_nonneg K hK _ (by intros; norm_num) t h lemma mass_le_one (K : List X → X → ℝ) (hK : ∀ h x,0 ≤ K h x) (hrow : ∀ h,∑ x,K h x ≤ 1) (t : ℕ) (h : List X) : mass K t h ≤ 1 := by induction t generalizing h with | zero => rfl | succ t ih => change (∑ x,K h x*mass K t (h++[x])) ≤ 1 calc _ ≤ ∑ x,K h x*1 := Finset.sum_le_sum (fun x _ => mul_le_mul_of_nonneg_left (ih _) (hK h x)) _ ≤ 1 := by simpa using hrow h theorem adaptive_success (K : List X → X → ℝ) (Good : List X → Prop) (hK : ∀ h x,0 ≤ K h x) (hrow : ∀ h,∑ x,K h x ≤ 1) (hsupport : ∀ h,Good h → ∀ x,0 simp [mass,expect] | succ t ih => have hlocal : ∀ x,K h x*(1-(t:ℝ)*e) ≤ K h x*mass K t (h++[x]) := by intro x by_cases hz : K h x=0 · simp [hz] · exact mul_le_mul_of_nonneg_left (ih _ (hsupport h hh x (lt_of_le_of_ne (hK h x) (Ne.symm hz)))) (hK h x) change 1-((t+1:ℕ):ℝ)*e ≤ ∑ x,K h x*mass K t (h++[x]) have hs := Finset.sum_le_sum (fun x (_ : x∈Finset.univ) => hlocal x) rw [← Finset.sum_mul] at hs have hm := hloss h hh have hu := hrow h have ht : 0 ≤ (t:ℝ)*e := mul_nonneg (Nat.cast_nonneg _) he push_cast nlinarith [mul_nonneg ht (sub_nonneg.mpr hu)] noncomputable def restrict (P : List X → X → ℝ) (Good : List X → Prop) (h : List X) (x : X) : ℝ := if Good (h++[x]) then P h x else 0 omit sectionInstance89 in lemma restrict_nonneg [Fintype X] (P : List X → X → ℝ) (Good : List X → Prop) (hP : ∀ h x,0 ≤ P h x) (h : List X) (x : X) : 0 ≤ restrict P Good h x := by unfold restrict; split_ifs; exact hP _ _; rfl omit sectionInstance89 in lemma restrict_le [Fintype X] (P : List X → X → ℝ) (Good : List X → Prop) (hP : ∀ h x,0 ≤ P h x) (h : List X) (x : X) : restrict P Good h x ≤ P h x := by unfold restrict; split_ifs; rfl; exact hP _ _ omit sectionInstance89 in lemma restrict_support [Fintype X] (P : List X → X → ℝ) (Good : List X → Prop) (h : List X) (x : X) (hx : 0 if Good l then 1 else 0) := by induction t generalizing h with | zero => simp [mass,expect,hh] | succ t ih => change (∑ x,restrict P Good h x*mass (restrict P Good) t (h++[x])) ≤ _ apply Finset.sum_le_sum intro x _ by_cases hg : Good (h++[x]) · simpa only [restrict,ite_eq_left hg] using mul_le_mul_of_nonneg_left (ih _ hg) (hP h x) · have hr : restrict P Good h x=0 := by simp [restrict,hg] rw [hr,zero_mul] exact mul_nonneg (hP h x) (expect_nonneg P hP _ (by intro l; split_ifs <;> norm_num) t _) theorem good_probability (P : List X → X → ℝ) (Good : List X → Prop) (hP : ∀ h x,0 ≤ P h x) (hrow : ∀ h,∑ x,P h x ≤ 1) (e : ℝ) (he : 0 ≤ e) (hstep : ∀ h,Good h → 1-e ≤ ∑ x,restrict P Good h x) (t : ℕ) (h : List X) (hh : Good h) : 1-(t:ℝ)*e ≤ expect P t h (fun l => if Good l then 1 else 0) := by have hb := adaptive_success (restrict P Good) Good (restrict_nonneg P Good hP) (fun h => (Finset.sum_le_sum (fun x _ => restrict_le P Good hP h x)).trans (hrow h)) (fun h _ x hx => restrict_support P Good h x hx) e he hstep t h hh exact hb.trans (mass_le_good_probability P Good hP t h hh) end FiniteExperiment section PairedSlots open scoped BigOperators Classical variable {α : Type*} [sectionInstance90 : Fintype α] [sectionInstance91 : DecidableEq α] def slotPair (i : α) : (α ⊕ α) × (α ⊕ α) := (Sum.inl i,Sum.inr i) def pairedSlots (n : ℕ) : List ((Fin n ⊕ Fin n) × (Fin n ⊕ Fin n)) := (List.finRange n).map slotPair omit sectionInstance90 sectionInstance91 in lemma slotPairList_fresh [Fintype α] [DecidableEq α] (l : List α) (hl : l.Nodup) (B : Set (α ⊕ α)) (hB : ∀ i ∈ l,Sum.inl i ∉ B ∧ Sum.inr i ∉ B) : SlotsFresh (l.map slotPair) B := by induction l generalizing B with | nil => trivial | cons a l ih => obtain ⟨ha,hl⟩ := List.nodup_cons.mp hl refine ⟨by simp [slotPair],(hB a (by simp)).1,(hB a (by simp)).2,?_⟩ apply ih hl intro i hi have hn : i ≠ a := fun he => ha (he ▸ hi) have hb := hB i (by simp [hi]) simpa [slotPair,hn] using hb lemma pairedSlots_fresh (n : ℕ) : SlotsFresh (pairedSlots n) ∅ := slotPairList_fresh _ (List.nodup_finRange n) ∅ (by intros; simp) @[simp] lemma pairedSlots_length (n : ℕ) : (pairedSlots n).length = n := by simp [pairedSlots] lemma pairedSlots_ne_nil (n : ℕ) (hn : 0 exact ⟨slotPair i,by simp [pairedSlots],Or.inl rfl⟩ | inr i => exact ⟨slotPair i,by simp [pairedSlots],Or.inr rfl⟩ lemma pairedSlots_plain (n : ℕ) (S : Set (Fin n ⊕ Fin n)) : PlainState (pairedSlots n) S ↔ ∀ i, (Sum.inl i ∈ S ↔ Sum.inr i ∉ S) := by simp only [PlainState,pairedSlots,List.mem_map,forall_exists_index,and_imp] constructor · intro h i have hh := h (slotPair i) i (by simp) rfl simp only [PairSingle,slotPair] at hh tauto · intro h p i hi he subst p have hh := h i simp only [PairSingle,slotPair] tauto lemma transversal_plain (n : ℕ) (A : Set (Fin n)) : PlainState (pairedSlots n) (transversal A) := by rw [pairedSlots_plain] intro i have hl : Sum.inl i ∈ transversal A ↔ i ∈ A := by change i ∈ Sum.inl ⁻¹' transversal A ↔ _ rw [preimage_inl_transversal] have hr : Sum.inr i ∈ transversal A ↔ i ∉ A := by change i ∈ Sum.inr ⁻¹' transversal A ↔ _ rw [preimage_inr_transversal]; rfl rw [hl,hr,not_not] lemma plain_eq_transversal (n : ℕ) (S : Set (Fin n ⊕ Fin n)) (hS : PlainState (pairedSlots n) S) : S = transversal (Sum.inl ⁻¹' S) := by rw [pairedSlots_plain] at hS ext x cases x with | inl i => change i ∈ Sum.inl ⁻¹' S ↔ i ∈ Sum.inl ⁻¹' transversal (Sum.inl ⁻¹' S) rw [preimage_inl_transversal] | inr i => change Sum.inr i ∈ S ↔ i ∈ Sum.inr ⁻¹' transversal (Sum.inl ⁻¹' S) rw [preimage_inr_transversal] change Sum.inr i ∈ S ↔ Sum.inl i ∉ S have hh := hS i tauto noncomputable def plainEquivSubsets (n : ℕ) : {S : Set (Fin n ⊕ Fin n) // PlainState (pairedSlots n) S} ≃ Set (Fin n) where toFun S := Sum.inl ⁻¹' S.val invFun A := ⟨transversal A,transversal_plain n A⟩ left_inv S := Subtype.ext (plain_eq_transversal n S.val S.property).symm right_inv A := preimage_inl_transversal A lemma pairedPlain_card (n : ℕ) : Fintype.card {S : Set (Fin n ⊕ Fin n) // PlainState (pairedSlots n) S} = 2^n := by rw [Fintype.card_congr (plainEquivSubsets n),Fintype.card_set,Fintype.card_fin] end PairedSlots open scoped BigOperators Classical noncomputable def subsetDeficiency {n : ℕ} (M₁ M₂ : Matroid (Fin n)) (A : Set (Fin n)) : ℕ := n-((pairedMatroid M₁ M₂).eRk (transversal A)).toNat lemma subsetDeficiency_zero {n : ℕ} (M₁ M₂ : Matroid (Fin n)) (hE₂ : M₂.E=Set.univ) (hr : M₁.eRank=M₂.eRank) (A : Set (Fin n)) : subsetDeficiency M₁ M₂ A=0 ↔ M₁.IsBase A ∧ M₂.IsBase A := by have hR : (pairedMatroid M₁ M₂).eRank=(n:ℕ∞) := by simpa using paired_eRank M₁ M₂ hE₂ hr have hk : ((pairedMatroid M₁ M₂).eRk (transversal A)).toNat≤n := ENat.toNat_le_of_le_natCast (by rw [← hR]; exact Matroid.eRk_le_eRank _ _) rw [← transversal_isBase_iff M₁ M₂ hE₂ A] constructor · intro hd have hn : ((pairedMatroid M₁ M₂).eRk (transversal A)).toNat=n := by unfold subsetDeficiency at hd; omega have he : (pairedMatroid M₁ M₂).eRk (transversal A)=(n:ℕ∞) := by calc _ = (((pairedMatroid M₁ M₂).eRk (transversal A)).toNat:ℕ∞) := (ENat.natCast_toNat (Matroid.isRkFinite_set _ _).eRk_lt_top.ne).symm _ = _ := congrArg (fun k : ℕ => (k:ℕ∞)) hn have hi : (pairedMatroid M₁ M₂).Indep (transversal A) := by apply (Matroid.indep_iff_eRk_eq_encard_of_finite (Set.toFinite _)).mpr rw [he,transversal_encard,Fintype.card_fin] exact hi.isBase_of_eRk_ge (Set.toFinite _) (by rw [he,hR]) · intro h unfold subsetDeficiency rw [h.eRk_eq_eRank,hR,ENat.toNat_natCast,Nat.sub_self] noncomputable def commonSetFinsetEquiv {n : ℕ} (M₁ M₂ : Matroid (Fin n)) : {A : Set (Fin n) // M₁.IsBase A ∧ M₂.IsBase A} ≃ {A : Finset (Fin n) // M₁.IsBase (A:Set (Fin n)) ∧ M₂.IsBase (A:Set (Fin n))} where toFun A := ⟨A.val.toFinset,by simpa only [Set.coe_toFinset] using A.property⟩ invFun A := ⟨(A.val:Set (Fin n)),A.property⟩ left_inv A := by apply Subtype.ext; exact Set.coe_toFinset _ right_inv A := by apply Subtype.ext; simp lemma zeroDeficiency_eq_commonBaseCount {n : ℕ} (M₁ M₂ : Matroid (Fin n)) (hE₂ : M₂.E=Set.univ) (hr : M₁.eRank=M₂.eRank) : zeroDeficiencyCount (subsetDeficiency M₁ M₂)=commonBaseCount M₁ M₂ := by have hp : (fun A => subsetDeficiency M₁ M₂ A=0) = (fun A => M₁.IsBase A ∧ M₂.IsBase A) := funext (fun A => propext (subsetDeficiency_zero M₁ M₂ hE₂ hr A)) unfold zeroDeficiencyCount commonBaseCount rw [← Fintype.card_subtype,← Nat.card_eq_fintype_card] calc _ = Nat.card {A : Set (Fin n) // M₁.IsBase A ∧ M₂.IsBase A} := Nat.card_congr (Equiv.subtypeEquivRight (fun A => subsetDeficiency_zero M₁ M₂ hE₂ hr A)) _ = _ := Nat.card_congr (commonSetFinsetEquiv M₁ M₂) lemma plainPartition_eq_subsets {n : ℕ} (M₁ M₂ : Matroid (Fin n)) (q : ℝ) : slotTotal (pairedSlots n) (matroidWeight (pairedMatroid M₁ M₂) n q) ∅ = deficiencyPartition (subsetDeficiency M₁ M₂) q := by rw [slotTotal_eq_plain_sum (pairedSlots n) (pairedSlots_fresh n) (pairedSlots_cover n)] rw [Finset.sum_subtype (p := PlainState (pairedSlots n)) _ (by intro S; simp)] unfold deficiencyPartition apply Fintype.sum_equiv (plainEquivSubsets n) intro S change q^(n-((pairedMatroid M₁ M₂).eRk S.val).toNat)= q^(n-((pairedMatroid M₁ M₂).eRk (transversal (Sum.inl ⁻¹' S.val))).toNat) rw [← plain_eq_transversal n S.val S.property] theorem paired_partition_contamination {n : ℕ} (M₁ M₂ : Matroid (Fin n)) (hE₂ : M₂.E=Set.univ) (hr : M₁.eRank=M₂.eRank) (q : ℝ) (hq0 : 0≤q) (hq1 : q≤1) : (commonBaseCount M₁ M₂:ℝ) ≤ slotTotal (pairedSlots n) (matroidWeight (pairedMatroid M₁ M₂) n q) ∅ ∧ slotTotal (pairedSlots n) (matroidWeight (pairedMatroid M₁ M₂) n q) ∅ ≤ (commonBaseCount M₁ M₂:ℝ)+(2:ℝ)^n*q := by have h := partition_contamination (subsetDeficiency M₁ M₂) q hq0 hq1 rw [zeroDeficiency_eq_commonBaseCount M₁ M₂ hE₂ hr,Fintype.card_set,Fintype.card_fin] at h rw [plainPartition_eq_subsets] exact_mod_cast h open scoped BigOperators Classical lemma annealRho_pow_upper (n : ℕ) (hn : 0 pow_le_one₀ hq0 hq1) _ = _ := by simp lemma anneal_minimum_mass {X : Type*} [Fintype X] [Nonempty X] (n L j : ℕ) (hn : 0 simp [FiniteKernel.power,FiniteKernel.identity] | succ k ih => change (∑ y,(∑ z,(C.kernel.power k).P x z*C.P z y)*f y)=_ simp_rw [Finset.sum_mul,mul_assoc] rw [Finset.sum_comm] simp_rw [← Finset.mul_sum] change (∑ z,(C.kernel.power k).P x z*C.apply f z)=_ rw [ih] exact congrFun (Function.iterate_succ_apply C.apply k f).symm x lemma kernel_power_density (k : ℕ) (x y : X) : (C.kernel.power k).P x y/C.π y=C.iterate k (C.pointDensity y) x := by rw [← C.kernel_power_action] simp [pointDensity,div_eq_mul_inv] lemma kernel_point_mixing (K m : ℝ) (hK : 1≤K) (hm : 0 < m) (hπ : ∀ x,m≤C.π x) (hp : ∀ f : X → ℝ,C.variance f≤K*C.energy f) (k : ℕ) (x y : X) : |(C.kernel.power k).P x y/C.π y-1|≤Real.exp (-(k:ℝ)/K)/m := by rw [C.kernel_power_density] exact C.point_mixing_exp K m hK hm hπ hp k x y lemma kernel_power_warm_any (K m e : ℝ) (hK : 1≤K) (hm : 0 < m) (hπ : ∀ x,m≤C.π x) (hp : ∀ f : X → ℝ,C.variance f≤K*C.energy f) (k : ℕ) (he : Real.exp (-(k:ℝ)/K)/m≤e) (he' : 0≤1+e) (ν : X → ℝ) (hν : ∀ x,0≤ν x) (hnorm : ∑ x,ν x≤1) (y : X) : (C.kernel.power k).push ν y≤(1+e)*C.π y := by have hrow : ∀ x,(C.kernel.power k).P x y≤(1+e)*C.π y := by intro x have h := (le_abs_self _).trans ((C.kernel_point_mixing K m hK hm hπ hp k x y).trans he) apply (div_le_iff₀ (C.positive y)).mp linarith calc _ ≤ ∑ x,ν x*((1+e)*C.π y) := Finset.sum_le_sum (fun x _ => mul_le_mul_of_nonneg_left (hrow x) (hν x)) _ = (∑ x,ν x)*((1+e)*C.π y) := by rw [Finset.sum_mul] _ ≤ _ := by simpa using mul_le_mul_of_nonneg_right hnorm (mul_nonneg he' (C.positive y).le) end FiniteChain namespace Annealing lemma restart_exponential (n L : ℕ) (hn : 0 exact h A | cons p ps ih => change coeffDeriv (pairDirection p) (slotTotal ps f) A ≤ coeffDeriv (pairDirection p) (slotTotal ps g) A unfold coeffDeriv apply Finset.sum_le_sum intro i _ split_ifs · rfl · exact mul_le_mul_of_nonneg_left (ih _) (slotDirection_nonneg _ _) lemma slotTotal_scale (ps : List (Γ × Γ)) (f : Set Γ → ℝ) (c : ℝ) (A : Set Γ) : slotTotal ps (fun S => c*f S) A=c*slotTotal ps f A := coeffDerivs_scale _ _ _ _ noncomputable def annealWeight (M : Matroid Γ) (n j : ℕ) : Set Γ → ℝ := matroidWeight M n (annealRho n^j) lemma annealWeight_pos (M : Matroid Γ) (n j : ℕ) (hn : 0 (annealWeight_drift M n j hn S).1) _ · exact slotTotal_mono _ _ _ (fun S => (annealWeight_drift M n j hn S).2) _ lemma anneal_ideal_drift (ps : List (Γ × Γ)) (hps : SlotsFresh ps ∅) (M : Matroid Γ) (n j : ℕ) (hn : 0 annealRho n^(n-(M.eRk S).toNat))) = slotTotal gs (annealWeight M n (j+1)) ∅/chainTotal gs w (annealWeight M n j) := by rw [plainObservable_mean gs hgs hcover] congr 2 funext S exact (annealWeight_step M n j hn S).symm lemma plain_probability_mean (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hcover : pairSupport gs=Set.univ) (f : Set Γ → ℝ) (w : (Γ × Γ) → (Γ × Γ) → ℝ) : chainMean gs w f (plainObservable gs (fun _ => 1))=slotTotal gs f ∅/chainTotal gs w f := by rw [plainObservable_mean gs hgs hcover] simp lemma weight_mean_identity (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hcover : pairSupport gs=Set.univ) (f : Set Γ → ℝ) (hf : ∀ S,0 1))/ chainMean gs w f (defectIndicator gs p r))=slotTotal gs f ∅/slotDefect gs f ∅ p r := by rw [plain_probability_mean gs hgs hcover,defectIndicator_mean gs hgs hcover _ _ p r hp hr hpr] field_simp [(chainTotal_pos gs hgs hcover w f hf hw).ne',(hw p r).ne'] lemma plainIndex_card (n : ℕ) : Fintype.card (PlainIndex (pairedSlots n))=2^n := by let e : PlainIndex (pairedSlots n) ≃ {S : Set (Fin n ⊕ Fin n) // PlainState (pairedSlots n) S} := { toFun := fun S => ⟨S.val.val,S.property⟩ invFun := fun S => ⟨⟨S.val,Or.inl S.property⟩,S.property⟩ left_inv := by intro S; rfl right_inv := by intro S; rfl } rw [Fintype.card_congr e,pairedPlain_card] lemma anneal_plainPartition (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hcover : pairSupport gs=Set.univ) (M : Matroid Γ) (n j : ℕ) : slotTotal gs (annealWeight M n j) ∅= deficiencyPartition (fun S : PlainIndex gs => n-(M.eRk S.val.val).toNat) (annealRho n^j) := by rw [slotTotal_eq_plain_sum gs hgs hcover] symm exact plainIndex_sum gs (annealWeight M n j) lemma actual_trace_minimum (n L j : ℕ) (hn : 0 n-(M.eRk S.val.val).toNat) (fun _ => Nat.sub_le _ _) S lemma slotTotal_one (ps : List (Γ × Γ)) (A : Set Γ) (hps : SlotsFresh ps A) : slotTotal ps (fun _ => 1) A=(2:ℝ)^ps.length := by induction ps generalizing A with | nil => rfl | cons p ps ih => rw [slotTotal_cons p ps _ A hps.1 hps.2.1 hps.2.2.1] have hleft : SlotsFresh ps (insert p.1 A) := hps.2.2.2.mono (by intro i hi; simp only [Set.mem_insert_iff] at hi ⊢; tauto) have hright : SlotsFresh ps (insert p.2 A) := hps.2.2.2.mono (by intro i hi; simp only [Set.mem_insert_iff] at hi ⊢; tauto) rw [ih _ hleft,ih _ hright,List.length_cons,pow_succ] ring lemma initial_ideal (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (p r : Γ × Γ) (hp : p∈gs) (hr : r∈gs) (hpr : p≠r) : slotTotal gs (fun _ => 1) ∅/slotDefect gs (fun _ => 1) ∅ p r=4 := by have hperm := slots_perm_two hp hr hpr have hh := (SlotsFresh.perm hperm ∅).mp hgs have hrest : SlotsFresh ((gs.erase p).erase r) (insert r.1 (insert r.2 ∅)) := hh.2.2.2.2.2.2.mono (by intro i hi; simp only [Set.mem_insert_iff] at hi ⊢; tauto) have hlen := List.Perm.length_eq hperm simp only [List.length_cons] at hlen rw [slotTotal_one _ _ hgs,slotDefect,slotTotal_one _ _ hrest,hlen,pow_succ,pow_succ] have hp : (2:ℝ)^((gs.erase p).erase r).length≠0 := by positivity field_simp ; ring lemma initial_good (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (M : Matroid Γ) (n : ℕ) : GoodMultipliers gs (annealWeight M n 0) (fun _ _ => 4) := by have he : annealWeight M n 0=(fun _ => 1) := by funext S; simp [annealWeight,matroidWeight] rw [he] refine ⟨by intros; norm_num,?_,?_⟩ · intro p hp r hr hpr rw [mul_comm (4:ℝ),← div_div,initial_ideal gs hgs p r hp hr hpr] norm_num · intro p hp r hr hpr rw [mul_div_assoc,initial_ideal gs hgs p r hp hr hpr] norm_num noncomputable def empirical (H : Set Γ → ℝ) (l : List (Set Γ)) : ℝ := (l.map H).sum/(l.length:ℝ) noncomputable def learnedMultipliers (gs : List (Γ × Γ)) (w : (Γ × Γ) → (Γ × Γ) → ℝ) (l : List (Set Γ)) (p r : Γ × Γ) : ℝ := if p∈gs ∧ r∈gs ∧ p≠r then w p r*(empirical (plainObservable gs (fun _ => 1)) l/empirical (defectIndicator gs p r) l) else w p r noncomputable def empiricalRatio (gs : List (Γ × Γ)) (g : Set Γ → ℝ) (l : List (Set Γ)) : ℝ := empirical (plainObservable gs g) l/empirical (plainObservable gs (fun _ => 1)) l def AccuratePhase (gs : List (Γ × Γ)) (w : (Γ × Γ) → (Γ × Γ) → ℝ) (f g : Set Γ → ℝ) (η : ℝ) (l : List (Set Γ)) : Prop := ∀ j : PhaseObservables gs, |empirical (phaseObservable gs g j) l-chainMean gs w f (phaseObservable gs g j)| ≤ η*chainMean gs w f (phaseObservable gs g j) lemma relative_error_bounds (x m η : ℝ) (h : |x-m| ≤ η*m) : (1-η)*m ≤ x ∧ x ≤ (1+η)*m := by obtain ⟨h1,h2⟩ := abs_le.mp h constructor <;> nlinarith lemma accurate_plain (gs : List (Γ × Γ)) (w : (Γ × Γ) → (Γ × Γ) → ℝ) (f g : Set Γ → ℝ) (η : ℝ) (l : List (Set Γ)) (h : AccuratePhase gs w f g η l) : (1-η)*chainMean gs w f (plainObservable gs (fun _ => 1)) ≤ empirical (plainObservable gs (fun _ => 1)) l ∧ empirical (plainObservable gs (fun _ => 1)) l ≤ (1+η)*chainMean gs w f (plainObservable gs (fun _ => 1)) := relative_error_bounds _ _ _ (h (.inl none)) lemma accurate_defect (gs : List (Γ × Γ)) (w : (Γ × Γ) → (Γ × Γ) → ℝ) (f g : Set Γ → ℝ) (η : ℝ) (l : List (Set Γ)) (h : AccuratePhase gs w f g η l) (p r : Γ × Γ) (hp : p∈gs) (hr : r∈gs) (hpr : p≠r) : (1-η)*chainMean gs w f (defectIndicator gs p r) ≤ empirical (defectIndicator gs p r) l ∧ empirical (defectIndicator gs p r) l ≤ (1+η)*chainMean gs w f (defectIndicator gs p r) := relative_error_bounds _ _ _ (h (.inl (some ⟨(p,r),(mem_defectTypes gs (p,r)).mpr ⟨hp,hr,hpr⟩⟩))) theorem successful_phase_learns (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hcover : pairSupport gs=Set.univ) (M : Matroid Γ) (n j : ℕ) (hn : 0 annealRho n^(n-(M.eRk S).toNat)) η l) : GoodMultipliers gs (annealWeight M n (j+1)) (learnedMultipliers gs w l) := by let f := annealWeight M n j let g := fun S => annealRho n^(n-(M.eRk S).toNat) have hf := annealWeight_pos M n j hn have hΛ := chainTotal_pos gs hgs hcover w f hf hw have hp0 : 0 1)) := by rw [plain_probability_mean gs hgs hcover] exact div_pos (slotTotal_pos gs f hf ∅ hgs) hΛ have hp0h := accurate_plain gs w f g η l hacc have hp0hp : 0 1)) l := lt_of_lt_of_le (mul_pos (by linarith) hp0) hp0h.1 have hpt : ∀ p∈gs,∀ r∈gs,p≠r → 0 annealRho n^(n-(M.eRk S).toNat)) η l) : (1-η)/(1+η) ≤ empiricalRatio gs (fun S => annealRho n^(n-(M.eRk S).toNat)) l/ (slotTotal gs (annealWeight M n (j+1)) ∅/slotTotal gs (annealWeight M n j) ∅) ∧ empiricalRatio gs (fun S => annealRho n^(n-(M.eRk S).toNat)) l/ (slotTotal gs (annealWeight M n (j+1)) ∅/slotTotal gs (annealWeight M n j) ∅) ≤ (1+η)/(1-η) := by let f := annealWeight M n j let g := fun S => annealRho n^(n-(M.eRk S).toNat) have hΛ := chainTotal_pos gs hgs hcover w f (annealWeight_pos M n j hn) hw have hp0 : 0 1)) := by rw [plain_probability_mean gs hgs hcover] exact div_pos (slotTotal_pos gs f (annealWeight_pos M n j hn) ∅ hgs) hΛ have hu : 0 1)) = slotTotal gs (annealWeight M n (j+1)) ∅/slotTotal gs (annealWeight M n j) ∅ := by rw [anneal_ratio_mean gs hgs hcover M n j hn,plain_probability_mean gs hgs hcover] dsimp only [f] at hΛ ⊢ field_simp [hΛ.ne'] have h := estimated_ratio_bounds η _ _ _ _ hη0 hη1 hp0 hu (accurate_plain gs w f g η l hacc) (relative_error_bounds _ _ _ (hacc (.inr ()))) rw [he] at h exact h.2 end ActualAnnealing namespace FiniteChain open scoped BigOperators Classical variable {X : Type*} [Fintype X] (C : FiniteChain X) lemma capped_power_submass (K : FiniteKernel X X) (hK : ∀ x y,K.P x y ≤ C.P x y) (ν : X → ℝ) (hν : ∀ x,0 ≤ ν x) (U e : ℝ) (hwarm : ∀ x,ν x ≤ U*C.π x) (hloss : ∀ a : X → ℝ,(∀ x,0 ≤ a x) → (∀ x,a x ≤ U*C.π x) → (∑ x,a x*(1-∑ y,K.P x y)) ≤ e) (T : ℕ) : (∑ x,ν x)-(∑ x,(K.power T).push ν x) ≤ (T:ℝ)*e := by have hdom := fun n x => K.power_domination C.kernel hK n ν hν x induction T with | zero => simp [FiniteKernel.power,FiniteKernel.push_identity] | succ T ih => have h := K.one_step_defect C.kernel C.stochastic ((K.power T).push ν) ((C.kernel.power T).push ν) ((K.power T).push_nonneg ν hν) (hdom T) have hl := hloss ((C.kernel.power T).push ν) ((C.kernel.power T).push_nonneg ν hν) (C.power_warm T ν U hwarm) have hm := C.power_push_mass T ν have hm' := C.power_push_mass (T+1) ν rw [FiniteKernel.power_push_succ] at hm' rw [FiniteKernel.power_push_succ] rw [hm,hm'] at h push_cast linarith variable (A : X → Prop) (Q : KilledKernel (Outside A)) (hQ : ∀ x y,Q.Q x y=C.P x.val y.val) lemma cappedTrace_power_submass [Nonempty (Inside A)] (N T : ℕ) (hN : 0 pairedSlots n local notation "W" => (((Fin n ⊕ Fin n) × (Fin n ⊕ Fin n)) → ((Fin n ⊕ Fin n) × (Fin n ⊕ Fin n)) → ℝ) noncomputable def actualTrace (j : ℕ) (w : W) (hw : ∀ p r,0 pairedSlots n local notation "W" => (((Fin n ⊕ Fin n) × (Fin n ⊕ Fin n)) → ((Fin n ⊕ Fin n) × (Fin n ⊕ Fin n)) → ℝ) noncomputable def actualCappedTrace (j : ℕ) (w : W) (hw : ∀ p r,0 1) := by funext S; simp [annealWeight,matroidWeight] rw [he,slotTotal_one GS ∅ (pairedSlots_fresh n),pairedSlots_length] rfl noncomputable def restartLaw (L cap : ℕ) (w : ℕ → W) (hw : ∀ j p r,0 uniformPlain n | j+1 => ((actualCappedTrace n hn M (j+1) (w (j+1)) (hw (j+1)) cap).power (20*n^4*(n*(L+1)+2))).push (restartLaw L cap w hw j) lemma restartLaw_nonneg (L cap : ℕ) (w : ℕ → W) (hw : ∀ j p r,0 simp only [restartLaw,uniformPlain]; positivity | succ j ih => exact FiniteKernel.push_nonneg _ _ ih x lemma restartLaw_mass_le (L cap : ℕ) (w : ℕ → W) (hw : ∀ j p r,0 exact (uniformPlain_mass n).le | succ j ih => exact (FiniteKernel.push_mass_le _ _ (restartLaw_nonneg n hn M L cap w hw j)).trans ih lemma restartLaw_warm (hE : M.E=Set.univ) (hR : M.eRank=(n:ℕ∞)) (L cap : ℕ) (w : ℕ → W) (hw : ∀ j p r,0 rw [restartLaw,uniformPlain_pi n hn M (w 0) (hw 0)] have h := (actualTrace n hn M 0 (w 0) (hw 0)).positive x linarith | succ j => have h := actual_capped_mixing n hn M hE hR L (j+1) hj (w (j+1)) hgood cap (restartLaw n hn M L cap w hw j) (restartLaw_nonneg n hn M L cap w hw j) (restartLaw_mass_le n hn M L cap w hw j) x change _ ≤ 2*(actualTrace n hn M (j+1) (w (j+1)) (hw (j+1))).π x have hp := (actualTrace n hn M (j+1) (w (j+1)) (hw (j+1))).positive x exact h.trans (by linarith) lemma restartLaw_missing_mass (hE : M.E=Set.univ) (hR : M.eRank=(n:ℕ∞)) (L cap : ℕ) (hcap : 0 simp [restartLaw,uniformPlain_mass] | succ j ih => have hj' : j ≤ L := by omega have hb := ih hj' (fun a ha => hgood a (by omega)) have hwarm : ∀ x,restartLaw n hn M L cap w hw j x ≤ 4*(actualTrace n hn M (j+1) (w (j+1)) (hw (j+1))).π x := by intro x have h1 := restartLaw_warm n hn M hE hR L cap w hw j hj' (hgood j (by omega)) x have h2 := actual_mu_drift n hn M j (w j) (w (j+1)) (hw j) (hw (j+1)) x linarith have h := actual_capped_loss n hn M (j+1) (w (j+1)) (hgood (j+1) le_rfl) cap (20*n^4*(n*(L+1)+2)) hcap (restartLaw n hn M L cap w hw j) (restartLaw_nonneg n hn M L cap w hw j) hwarm change 1-(∑ x,(_ : FiniteKernel _ _).push _ x) ≤ _ simp only [Nat.cast_add,Nat.cast_one] nlinarith end ActualRestart namespace FiniteChain open scoped BigOperators Classical variable {X : Type*} [Fintype X] (C : FiniteChain X) lemma pathProbability_congr_length (ν : X → ℝ) (N : ℕ) (E F : List X → Prop) (h : ∀ l,l.length=N+1 → (E l ↔ F l)) : C.pathProbability ν N E=C.pathProbability ν N F := by unfold pathProbability apply Finset.sum_congr rfl intro x _ congr 1 apply C.pathExpectation_congr_length intro l hl simp only [h l hl] lemma pathProbability_compl (ν : X → ℝ) (N : ℕ) (E : List X → Prop) : C.pathProbability ν N E+C.pathProbability ν N (fun l => ¬E l)=∑ x,ν x := by unfold pathProbability rw [← Finset.sum_add_distrib] apply Finset.sum_congr rfl intro x _ rw [← mul_add,← C.pathExpectation_add] calc _ = ν x*C.pathExpectation N x (fun _ => 1) := by congr 1 apply C.pathExpectation_congr intro l by_cases h : E l <;> simp [h] _ = ν x := by rw [C.pathExpectation_const,mul_one] lemma pathProbability_le_mass (ν : X → ℝ) (hν : ∀ x,0 ≤ ν x) (N : ℕ) (E : List X → Prop) : C.pathProbability ν N E ≤ ∑ x,ν x := by have h := C.pathProbability_compl ν N E have hn := C.pathProbability_nonneg ν hν N (fun l => ¬E l) linarith end FiniteChain section PhaseBridge open scoped BigOperators Classical variable {Γ : Type*} [sectionInstance97 : Fintype Γ] [sectionInstance98 : DecidableEq Γ] omit sectionInstance97 sectionInstance98 in lemma empirical_trajectory [Fintype Γ] [DecidableEq Γ] (gs : List (Γ × Γ)) (H : Set Γ → ℝ) (l : List (ChainIndex gs)) : empirical H (l.map Subtype.val)=FiniteChain.pathSum (fun S => H S.val) l/(l.length:ℝ) := by simp [empirical,FiniteChain.pathSum,] theorem accurate_phase_probability (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hne : gs≠[]) (hcover : pairSupport gs=Set.univ) (w : (Γ × Γ) → (Γ × Γ) → ℝ) (f g : Set Γ → ℝ) (hw : GoodMultipliers gs f w) (hf : ∀ S,0 AccuratePhase gs w f g η (l.map Subtype.val)) := by let C := metropolisChain gs hgs hne hcover w f hw.positive hf have hn : 0 ∃ j : PhaseObservables gs,η*C.mean (fun S => phaseObservable gs g j S.val)< |FiniteChain.pathSum (fun S => phaseObservable gs g j S.val) l/(N:ℝ)-C.mean (fun S => phaseObservable gs g j S.val)|) (fun l => ¬AccuratePhase gs w f g η (l.map Subtype.val)) (by intro l hl have hl' : l.length=N := by omega simp only [AccuratePhase,empirical_trajectory,hl',not_forall,not_le] simp only [C,metropolisChain_mean]) rw [he] at h have hc := C.pathProbability_compl ν (N-1) (fun l => AccuratePhase gs w f g η (l.map Subtype.val)) dsimp only linarith end PhaseBridge section EstimatorBridge open scoped BigOperators Classical variable {Γ : Type*} [Fintype Γ] [DecidableEq Γ] lemma product_ratios_telescope (a : ℕ → ℝ) (ha : ∀ j,a j≠0) (L : ℕ) : (∏ j ∈ Finset.range L,a (j+1)/a j)=a L/a 0 := by induction L with | zero => simp [ha] | succ L ih => rw [Finset.prod_range_succ,ih]; field_simp [ha L,ha 0] lemma accurate_phases_product (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hcover : pairSupport gs=Set.univ) (M : Matroid Γ) (n : ℕ) (hn : 0 annealRho n^(n-(M.eRk S).toNat)) (annealTolerance ε L) (ls j)) : let Zhat := (2:ℝ)^gs.length * ∏ j ∈ Finset.range L, empiricalRatio gs (fun S => annealRho n^(n-(M.eRk S).toNat)) (ls j) (1-ε/4)*slotTotal gs (annealWeight M n L) ∅ ≤ Zhat ∧ Zhat ≤ (1+ε/4)*slotTotal gs (annealWeight M n L) ∅ := by let c := fun j => slotTotal gs (annealWeight M n j) ∅ let R := fun j => empiricalRatio gs (fun S => annealRho n^(n-(M.eRk S).toNat)) (ls j) have hc : ∀ j,0 slotTotal_pos gs _ (annealWeight_pos M n j hn) ∅ hgs have ht := product_ratios_telescope c (fun j => (hc j).ne') L have he : c 0=(2:ℝ)^gs.length := by have hf : annealWeight M n 0=(fun _ => 1) := by funext S; simp [annealWeight,matroidWeight] dsimp only [c]; rw [hf,slotTotal_one gs ∅ hgs] have hη : 0 R j/(c (j+1)/c j)) ε L hε0 hε1 (fun j hj => successful_phase_ratio gs hgs hcover M n j hn (w j) (hw j) (annealTolerance ε L) hη.1.le (by linarith [hη.2]) (ls j) (hacc j hj)) have hidentity : (∏ j ∈ Finset.range L,R j/(c (j+1)/c j)) = ((2:ℝ)^gs.length*(∏ j ∈ Finset.range L,R j))/c L := by rw [Finset.prod_div_distrib,ht,he] field_simp rw [hidentity] at hp constructor · exact (le_div_iff₀ (hc L)).mp hp.1 · exact (div_le_iff₀ (hc L)).mp hp.2 theorem actual_estimator_accuracy {n : ℕ} (hn : 0 annealRho n^(n-((pairedMatroid M₁ M₂).eRk S).toNat)) (annealTolerance ε (annealLength n b)) (ls j)) : let Zhat := (2:ℝ)^n * ∏ j ∈ Finset.range (annealLength n b), empiricalRatio (pairedSlots n) (fun S => annealRho n^(n-((pairedMatroid M₁ M₂).eRk S).toNat)) (ls j) (1-ε)*(commonBaseCount M₁ M₂:ℝ) ≤ Zhat ∧ Zhat ≤ (1+ε)*(commonBaseCount M₁ M₂:ℝ) := by have hp := accurate_phases_product (pairedSlots n) (pairedSlots_fresh n) (pairedSlots_cover n) (pairedMatroid M₁ M₂) n hn ε hε0 hε1 (annealLength n b) w hw ls hacc simp only [pairedSlots_length] at hp have hrho := annealRho_bounds n hn have hq0 : 0 ≤ annealRho n^annealLength n b := pow_nonneg (le_trans (by norm_num) hrho.1) _ have hq1 : annealRho n^annealLength n b ≤ 1 := pow_le_one₀ (le_trans (by norm_num) hrho.1) hrho.2.le have hc := paired_partition_contamination M₁ M₂ hE₂ hr _ hq0 hq1 have hcont := anneal_final_contamination n b hn ε hb have hZ' : (1:ℝ) ≤ commonBaseCount M₁ M₂ := by exact_mod_cast hZ apply final_estimate_accuracy ε _ _ _ hε0 hε1 (by positivity) ⟨hc.1,?_⟩ hp have hm := mul_le_mul_of_nonneg_left hZ' (show 0 ≤ ε/10 by positivity) nlinarith [hc.2] end EstimatorBridge namespace FiniteChain open scoped BigOperators Classical variable {X : Type*} [sectionInstance101 : Fintype X] universe u def Sample (X : Type u) : ℕ → Type u | 0 => X | k+1 => X × Sample X k instance sampleFintype (k : ℕ) : Fintype (Sample X k) := by induction k with | zero => exact inferInstanceAs (Fintype X) | succ k ih => letI : Fintype (Sample X k) := ih exact inferInstanceAs (Fintype (X × Sample X k)) def Sample.toList : {k : ℕ} → Sample X k → List X | 0,x => [x] | _+1,(x,v) => x::v.toList omit sectionInstance101 in lemma Sample.toList_length [Fintype X] {k : ℕ} (v : Sample X k) : v.toList.length=k+1 := by induction k with | zero => rfl | succ k ih => exact congrArg Nat.succ (ih v.2) variable (C : FiniteChain X) noncomputable def sampleMass (C : FiniteChain X) (ν : X → ℝ) : {k : ℕ} → Sample X k → ℝ | 0,x => ν x | _+1,(x,v) => ν x*sampleMass C (C.P x) v lemma sampleMass_nonneg (ν : X → ℝ) (hν : ∀ x,0 ≤ ν x) {k : ℕ} (v : Sample X k) : 0 ≤ C.sampleMass ν v := by induction k generalizing ν with | zero => exact hν v | succ k ih => exact mul_nonneg (hν _) (ih _ (C.nonnegative _) v.2) lemma sampleMass_expect (ν : X → ℝ) (k : ℕ) (F : List X → ℝ) : (∑ v : Sample X k,C.sampleMass ν v*F v.toList)= ∑ x,ν x*C.pathExpectation k x F := by induction k generalizing ν F with | zero => rfl | succ k ih => change (∑ v : X × Sample X k,_)=_ rw [Fintype.sum_prod_type] apply Finset.sum_congr rfl intro x _ simp only [sampleMass,Sample.toList,mul_assoc,← Finset.mul_sum] rw [ih (C.P x) (fun l => F (x::l))] rfl lemma sampleMass_total (ν : X → ℝ) (k : ℕ) : (∑ v : Sample X k,C.sampleMass ν v)=∑ x,ν x := by have h := C.sampleMass_expect ν k (fun _ => 1) simpa only [mul_one,C.pathExpectation_const] using h lemma sampleMass_event (ν : X → ℝ) (k : ℕ) (E : List X → Prop) : (∑ v : Sample X k,if E v.toList then C.sampleMass ν v else 0)=C.pathProbability ν k E := by unfold pathProbability rw [← C.sampleMass_expect] apply Finset.sum_congr rfl intro v _ split_ifs <;> simp end FiniteChain section WarmLift open scoped BigOperators Classical variable {Γ : Type*} [sectionInstance102 : Fintype Γ] [sectionInstance103 : DecidableEq Γ] noncomputable def plainLift (gs : List (Γ × Γ)) (ν : PlainIndex gs → ℝ) (S : ChainIndex gs) : ℝ := if h : PlainState gs S.val then ν ⟨S,h⟩ else 0 omit sectionInstance102 sectionInstance103 in lemma plainLift_nonneg [Fintype Γ] [DecidableEq Γ] (gs : List (Γ × Γ)) (ν : PlainIndex gs → ℝ) (hν : ∀ x,0 ≤ ν x) (S : ChainIndex gs) : 0 ≤ plainLift gs ν S := by unfold plainLift; split_ifs; exact hν _; rfl omit sectionInstance103 in lemma plainLift_mass [DecidableEq Γ] (gs : List (Γ × Γ)) (ν : PlainIndex gs → ℝ) : (∑ S,plainLift gs ν S)=∑ S : PlainIndex gs,ν S := by have h := Fintype.sum_subtype_add_sum_subtype (plainPredicate gs) (fun S => plainLift gs ν S) have ht : ∀ S : PlainIndex gs,plainLift gs ν S.val=ν S := by intro S; exact dite_eq_left S.property have hf : ∀ S : {S : ChainIndex gs // ¬plainPredicate gs S},plainLift gs ν S.val=0 := by intro S; exact dite_eq_right S.property simp_rw [ht,hf,Finset.sum_const_zero,add_zero] at h exact h.symm lemma plainLift_warm (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hne : gs≠[]) (hcover : pairSupport gs=Set.univ) (w : (Γ × Γ) → (Γ × Γ) → ℝ) (f : Set Γ → ℝ) (hf : ∀ S,0 simp [mass,expect] | succ t ih => have hlocal : ∀ x,K h x*(1-(t:ℝ)*e) ≤ K h x*mass K t (h++[x]) := by intro x by_cases hz : K h x=0 · simp [hz] · exact mul_le_mul_of_nonneg_left (ih _ (hsupport h hh x (lt_of_le_of_ne (hK h x) (Ne.symm hz))) (by simp only [List.length_append,List.length_singleton]; omega)) (hK h x) change 1-((t+1:ℕ):ℝ)*e ≤ ∑ x,K h x*mass K t (h++[x]) have hs := Finset.sum_le_sum (fun x (_ : x∈Finset.univ) => hlocal x) rw [← Finset.sum_mul] at hs have hm := hloss h hh (by omega) have hu := hrow h have ht : 0 ≤ (t:ℝ)*e := mul_nonneg (Nat.cast_nonneg _) he push_cast nlinarith [mul_nonneg ht (sub_nonneg.mpr hu)] theorem good_probability_bounded (P : List X → X → ℝ) (Good : List X → Prop) (hP : ∀ h x,0 ≤ P h x) (hrow : ∀ h,∑ x,P h x ≤ 1) (L : ℕ) (e : ℝ) (he : 0 ≤ e) (hstep : ∀ h,Good h → h.length if Good l then 1 else 0) := by intro hh have hb := adaptive_success_bounded (restrict P Good) Good (restrict_nonneg P Good hP) (fun h => (Finset.sum_le_sum (fun x _ => restrict_le P Good hP h x)).trans (hrow h)) (fun h _ x hx => restrict_support P Good h x hx) L e he hstep L [] hh (by simp) exact hb.trans (mass_le_good_probability P Good hP L [] hh) end FiniteExperiment section ActualHistory open scoped BigOperators Classical variable {Γ : Type*} [sectionInstance105 : Fintype Γ] [DecidableEq Γ] variable (gs : List (Γ × Γ)) noncomputable def historyWeights {X : Type*} (sample : X → List (Set Γ)) (h : List X) : (Γ × Γ) → (Γ × Γ) → ℝ := h.foldl (fun w x => learnedMultipliers gs w (sample x)) (fun _ _ => 4) omit sectionInstance105 in lemma historyWeights_nil [Fintype Γ] {X : Type*} (sample : X → List (Set Γ)) : historyWeights gs sample []=(fun _ _ => 4) := rfl omit sectionInstance105 in lemma historyWeights_snoc [Fintype Γ] {X : Type*} (sample : X → List (Set Γ)) (h : List X) (x : X) : historyWeights gs sample (h++[x])=learnedMultipliers gs (historyWeights gs sample h) (sample x) := by simp [historyWeights,List.foldl_append] variable (M : Matroid Γ) (n : ℕ) (η : ℝ) inductive SuccessfulHistory {X : Type*} (sample : X → List (Set Γ)) : List X → Prop | nil : SuccessfulHistory sample [] | snoc (h : List X) (x : X) (hh : SuccessfulHistory sample h) (hx : AccuratePhase gs (historyWeights gs sample h) (annealWeight M n h.length) (fun S => annealRho n^(n-(M.eRk S).toNat)) η (sample x)) : SuccessfulHistory sample (h++[x]) lemma successfulHistory_take {X : Type*} (sample : X → List (Set Γ)) (h : List X) (hh : SuccessfulHistory gs M n η sample h) (a : ℕ) : SuccessfulHistory gs M n η sample (h.take a) := by induction hh with | nil => simpa using SuccessfulHistory.nil (gs := gs) (M := M) (n := n) (η := η) (sample := sample) | snoc h x hh hx ih => by_cases ha : a ≤ h.length · rw [List.take_append_of_le_length ha] exact ih · have he : a ≥ (h++[x]).length := by simp; omega rw [List.take_of_length_le he] exact SuccessfulHistory.snoc h x hh hx lemma successfulHistory_good {X : Type*} (sample : X → List (Set Γ)) (hgs : SlotsFresh gs ∅) (hcover : pairSupport gs=Set.univ) (hn : 0 exact initial_good gs hgs M n | snoc h x hh hx ih => rw [historyWeights_snoc,List.length_append,List.length_singleton] exact successful_phase_learns gs hgs hcover M n h.length hn (historyWeights gs sample h) ih.positive η hη0 hη1 (sample x) hx lemma successfulHistory_snoc_iff {X : Type*} (sample : X → List (Set Γ)) (h : List X) (x : X) (hh : SuccessfulHistory gs M n η sample h) : SuccessfulHistory gs M n η sample (h++[x]) ↔ AccuratePhase gs (historyWeights gs sample h) (annealWeight M n h.length) (fun S => annealRho n^(n-(M.eRk S).toNat)) η (sample x) := by constructor · intro hs have aux : ∀ l,SuccessfulHistory gs M n η sample l → ∀ h x,l=h++[x] → AccuratePhase gs (historyWeights gs sample h) (annealWeight M n h.length) (fun S => annealRho n^(n-(M.eRk S).toNat)) η (sample x) := by intro l hl h x he cases hl with | nil => simp at he | snoc l y hl hy => have hlen := congrArg List.length he simp only [List.length_append,List.length_singleton] at hlen have hex := List.append_inj he (by omega : l.length=h.length) obtain ⟨rfl,hyx⟩ := hex have : y=x := by simpa using hyx subst y exact hy exact aux _ hs h x rfl · exact SuccessfulHistory.snoc h x hh end ActualHistory section ActualPhase open scoped BigOperators Classical variable (n : ℕ) (hn : 0 pairedSlots n local notation "W" => (((Fin n ⊕ Fin n) × (Fin n ⊕ Fin n)) → ((Fin n ⊕ Fin n) × (Fin n ⊕ Fin n)) → ℝ) def restartCap (n L : ℕ) : ℕ := 2000*(L+1)^2*n^2*(20*n^4*(n*(L+1)+2)) include hn in lemma restartCap_pos (L : ℕ) : 0 pairedSlots n variable (N L : ℕ) (η : ℝ) (hη0 : 0<η) (hη1 : η ≤ 1/3) include hE hR hη0 hη1 in lemma phaseStart_warm (h : List (PhaseSample n N)) (hh : SuccessfulHistory GS M n η (observedSets n N) h) (hj : h.length ≤ L) : let hp := successfulHistory_positive n hn M N η hη0.le hη1 h hh ∀ S,phaseStart n hn M N L h hp S ≤ (10*(n:ℝ)^2)*chainWeight GS (storedWeights n N h h.length) (annealWeight M n h.length) S.val / chainTotal GS (storedWeights n N h h.length) (annealWeight M n h.length) := by intro hp S let good := successfulHistory_stored_good n hn M N η hη0.le hη1 h hh h.length le_rfl have hw := restartLaw_warm n hn M hE hR L (restartCap n L) (storedWeights n N h) (historyPositive_all n N h hp) h.length hj good simpa only [phaseStart,pairedSlots_length] using plainLift_warm GS (pairedSlots_fresh n) (pairedSlots_ne_nil n hn) (pairedSlots_cover n) (storedWeights n N h h.length) (annealWeight M n h.length) (annealWeight_pos M n h.length hn) good _ hw S include hE hR hη0 hη1 in lemma phaseStart_mass_lower (h : List (PhaseSample n N)) (hh : SuccessfulHistory GS M n η (observedSets n N) h) (hj : h.length ≤ L) : let hp := successfulHistory_positive n hn M N η hη0.le hη1 h hh 1-1/(100*(L+1:ℝ)) ≤ ∑ S,phaseStart n hn M N L h hp S := by intro hp have hm := restartLaw_missing_mass n hn M hE hR L (restartCap n L) (restartCap_pos n hn L) (storedWeights n N h) (historyPositive_all n N h hp) h.length hj (fun a ha => successfulHistory_stored_good n hn M N η hη0.le hη1 h hh a ha) have he := restartCap_loss n hn L h.length hj simp only [phaseStart,plainLift_mass] linarith include hE hR hη0 hη1 in lemma phaseKernel_good_mass (hN : (10:ℝ)^10*(L+1)*n^14/η^2 ≤ N) (h : List (PhaseSample n N)) (hh : SuccessfulHistory GS M n η (observedSets n N) h) (hj : h.length ≤ L) : 1-1/(20*(L+1:ℝ)) ≤ ∑ v,FiniteExperiment.restrict (phaseKernel n hn M N L) (SuccessfulHistory GS M n η (observedSets n N)) h v := by let hp := successfulHistory_positive n hn M N η hη0.le hη1 h hh let good := successfulHistory_stored_good n hn M N η hη0.le hη1 h hh h.length le_rfl have hrho := annealRho_bounds n hn have hρ : 0 annealRho n^(n-(M.eRk S).toNat)) good (annealWeight_pos M n h.length hn) hsig hg (phaseStart n hn M N L h hp) (phaseStart_nonneg n hn M N L h hp) (by simpa only [pairedSlots_length] using phaseStart_warm n hn M hE hR N L η hη0 hη1 h hh hj) L N η hη0 (by simpa only [pairedSlots_length] using hN) have he : (∑ v,FiniteExperiment.restrict (phaseKernel n hn M N L) (SuccessfulHistory GS M n η (observedSets n N)) h v) = (phaseChain n hn M N h hp).pathProbability (phaseStart n hn M N L h hp) (N-1) (fun l => AccuratePhase GS (storedWeights n N h h.length) (annealWeight M n h.length) (fun S => annealRho n^(n-(M.eRk S).toNat)) η (l.map Subtype.val)) := by rw [← FiniteChain.sampleMass_event] apply Finset.sum_congr rfl intro v _ simp only [FiniteExperiment.restrict,successfulHistory_snoc_iff GS M n η (observedSets n N) h v hh, phaseKernel,dite_eq_left hp,storedWeights_current,observedSets] rw [he] change (∑ S,phaseStart n hn M N L h hp S)-1/(32*(L+1:ℝ)) ≤ (phaseChain n hn M N h hp).pathProbability _ _ _ at ha have hm := phaseStart_mass_lower n hn M hE hR N L η hη0 hη1 h hh hj have he' : 1/(100*(L+1:ℝ))+1/(32*(L+1:ℝ)) ≤ 1/(20*(L+1:ℝ)) := by have hl : 0<(L:ℝ)+1 := by positivity field_simp nlinarith linarith include hE hR hη0 hη1 in theorem actual_history_success (hN : (10:ℝ)^10*(L+1)*n^14/η^2 ≤ N) : 19/20 ≤ FiniteExperiment.expect (phaseKernel n hn M N L) L [] (fun h => if SuccessfulHistory GS M n η (observedSets n N) h then 1 else 0) := by have h := FiniteExperiment.good_probability_bounded (phaseKernel n hn M N L) (SuccessfulHistory GS M n η (observedSets n N)) (phaseKernel_nonneg n hn M N L) (phaseKernel_mass_le n hn M N L) L (1/(20*(L+1:ℝ))) (by positivity) (fun h hh hj => phaseKernel_good_mass n hn M hE hR N L η hη0 hη1 hN h hh hj.le) SuccessfulHistory.nil apply le_trans _ h have hl : 0<(L:ℝ)+1 := by positivity apply (le_sub_iff_add_le).mpr field_simp nlinarith end PhaseSuccess section HistoryEstimate open scoped BigOperators Classical variable {Γ : Type*} [sectionInstance107 : Fintype Γ] [sectionInstance108 : DecidableEq Γ] variable {X : Type*} (sample : X → List (Set Γ)) def historySample (h : List X) (j : ℕ) : List (Set Γ) := (h[j]?.map sample).getD [] omit sectionInstance107 sectionInstance108 in lemma historySample_getElem [Fintype Γ] [DecidableEq Γ] (h : List X) (j : ℕ) (hj : j annealRho n^(n-(M.eRk S).toNat)) η (historySample sample h j) := by have ht := successfulHistory_take gs M n η sample h hh j have hs := successfulHistory_take gs M n η sample h hh (j+1) rw [List.take_succ_eq_append_getElem hj] at hs have ha := (successfulHistory_snoc_iff gs M n η sample (h.take j) h[j] ht).mp hs simpa only [List.length_take,Nat.min_eq_left hj.le,historySample_getElem sample h j hj] using ha end HistoryEstimate section ActualHistoryEstimate open scoped BigOperators Classical variable (n : ℕ) (N L : ℕ) (M : Matroid (Fin n ⊕ Fin n)) noncomputable def historyEstimate (h : List (PhaseSample n N)) : ℝ := (2:ℝ)^n * ∏ j ∈ Finset.range L, empiricalRatio (pairedSlots n) (fun S => annealRho n^(n-(M.eRk S).toNat)) (historySample (observedSets n N) h j) lemma historyEstimate_accuracy (hn : 0 successfulHistory_accurate (observedSets n N) (pairedSlots n) (pairedMatroid M₁ M₂) n (annealTolerance ε (annealLength n b)) h hh j (by omega)) lemma empirical_nonneg {Γ : Type*} (H : Set Γ → ℝ) (hH : ∀ S,0 ≤ H S) (l : List (Set Γ)) : 0 ≤ empirical H l := by unfold empirical apply div_nonneg _ (Nat.cast_nonneg _) exact List.sum_nonneg (fun x hx => by obtain ⟨S,hS,rfl⟩ := List.mem_map.mp hx; exact hH S) lemma empiricalRatio_nonneg {Γ : Type*} [Fintype Γ] [DecidableEq Γ] (gs : List (Γ × Γ)) (g : Set Γ → ℝ) (hg : ∀ S,0 ≤ g S) (l : List (Set Γ)) : 0 ≤ empiricalRatio gs g l := by unfold empiricalRatio apply div_nonneg · apply empirical_nonneg; intro S; unfold plainObservable; split_ifs; exact hg S; rfl · apply empirical_nonneg; intro S; unfold plainObservable; split_ifs <;> norm_num lemma historyEstimate_nonneg (hn : 0 pow_nonneg (le_trans (by norm_num) (annealRho_bounds n hn).1) _) _ end ActualHistoryEstimate section WitnessRestart open scoped BigOperators Classical variable (n : ℕ) (hn : 0 pairedMatroid M₁ M₂ local notation "GS" => pairedSlots n local notation "W" => (((Fin n ⊕ Fin n) × (Fin n ⊕ Fin n)) → ((Fin n ⊕ Fin n) × (Fin n ⊕ Fin n)) → ℝ) def Witnessed (x : PlainIndex GS) : Prop := n-((K).eRk x.val.val).toNat=0 lemma witnessed_iff_common_base (hE₂ : M₂.E=Set.univ) (hr : M₁.eRank=M₂.eRank) (x : PlainIndex GS) : Witnessed n M₁ M₂ x ↔ M₁.IsBase (Sum.inl ⁻¹' x.val.val) ∧ M₂.IsBase (Sum.inl ⁻¹' x.val.val) := by unfold Witnessed rw [plain_eq_transversal n x.val.val x.property] simpa only [preimage_inl_transversal,subsetDeficiency] using subsetDeficiency_zero M₁ M₂ hE₂ hr (Sum.inl ⁻¹' x.val.val) lemma witnessed_count_pos (hE₂ : M₂.E=Set.univ) (hr : M₁.eRank=M₂.eRank) (x : PlainIndex GS) (hx : Witnessed n M₁ M₂ x) : 0 hlocal x) simp only [Finset.sum_const,Finset.card_univ,nsmul_eq_mul,plainIndex_card,Nat.cast_pow,Nat.cast_ofNat] at hs have he := anneal_final_contamination n b hn ε hb dsimp only [q] at hs linarith variable (N : ℕ) noncomputable def witnessKernel (L : ℕ) (h : List (PhaseSample n N)) (x : PlainIndex GS) : ℝ := if hp : HistoryPositive n N h then restartLaw n hn K L (restartCap n L) (storedWeights n N h) (historyPositive_all n N h hp) h.length x else 0 lemma witnessKernel_nonneg (L : ℕ) (h : List (PhaseSample n N)) (x : PlainIndex GS) : 0 ≤ witnessKernel n hn M₁ M₂ N L h x := by unfold witnessKernel split_ifs with hp · exact restartLaw_nonneg n hn K L _ _ _ _ x · rfl lemma witnessKernel_mass_le (L : ℕ) (h : List (PhaseSample n N)) : (∑ x,witnessKernel n hn M₁ M₂ N L h x) ≤ 1 := by unfold witnessKernel split_ifs with hp · exact restartLaw_mass_le n hn K L _ _ _ _ · simp include hn in lemma witnessKernel_good_mass (hE₁ : M₁.E=Set.univ) (hE₂ : M₂.E=Set.univ) (hr : M₁.eRank=M₂.eRank) (ε : ℝ) (hε0 : 0<ε) (hε1 : ε<1) (b : ℕ) (hb : (1/2:ℝ)^b ≤ ε/10) (hZ : 0 simp have hsmall : 1/(100*(L+1:ℝ)) ≤ 1/100 := by apply (div_le_iff₀ (by positivity : (0:ℝ)<100*(L+1:ℝ))).mpr nlinarith [Nat.cast_nonneg (α := ℝ) L] have hm' : 99/100 ≤ ∑ x,witnessKernel n hn M₁ M₂ N L h x := by simp only [witnessKernel,dite_eq_left hp] linarith change 79/100 ≤ ∑ x,if Witnessed n M₁ M₂ x then witnessKernel n hn M₁ M₂ N L h x else 0 linarith end WitnessRestart namespace FiniteExperiment open scoped BigOperators Classical variable {X : Type*} [Fintype X] lemma expect_mul_left (K : List X → X → ℝ) (r : ℝ) (φ : List X → ℝ) (t : ℕ) (h : List X) : expect K t h (fun l => r*φ l)=r*expect K t h φ := by induction t generalizing h with | zero => rfl | succ t ih => simp only [expect,ih] rw [Finset.mul_sum] apply Finset.sum_congr rfl intro x _ ring lemma expect_mono_length (K : List X → X → ℝ) (hK : ∀ h x,0 ≤ K h x) (φ ψ : List X → ℝ) (t : ℕ) (h : List X) (hh : ∀ l,l.length=h.length+t → φ l ≤ ψ l) : expect K t h φ ≤ expect K t h ψ := by induction t generalizing h with | zero => exact hh h (by simp) | succ t ih => apply Finset.sum_le_sum intro x _ apply mul_le_mul_of_nonneg_left _ (hK h x) apply ih intro l hl apply hh l simp only [List.length_append,List.length_singleton] at hl omega end FiniteExperiment open scoped BigOperators Classical variable (n : ℕ) (hn : 0 pairedMatroid M₁ M₂ local notation "GS" => pairedSlots n noncomputable def guardedEstimate (h : List (PhaseSample n N)) (x : PlainIndex GS) : ℝ := if Witnessed n M₁ M₂ x then historyEstimate n N L K h else 0 include hn in lemma guardedEstimate_nonneg (h : List (PhaseSample n N)) (x : PlainIndex GS) : 0 ≤ guardedEstimate n M₁ M₂ N L h x := by unfold guardedEstimate split_ifs · exact historyEstimate_nonneg n N L K hn h · rfl lemma guardedEstimate_zero (hE₂ : M₂.E=Set.univ) (hr : M₁.eRank=M₂.eRank) (hZ : commonBaseCount M₁ M₂=0) (h : List (PhaseSample n N)) (x : PlainIndex GS) : guardedEstimate n M₁ M₂ N L h x=0 := by unfold guardedEstimate apply ite_eq_right intro hx have hp := witnessed_count_pos n M₁ M₂ hE₂ hr x hx omega noncomputable def actualRealSuccess (ε : ℝ) : ℝ := FiniteExperiment.expect (phaseKernel n hn K N L) L [] (fun h => ∑ x,if (1-ε)*(commonBaseCount M₁ M₂:ℝ) ≤ guardedEstimate n M₁ M₂ N L h x ∧ guardedEstimate n M₁ M₂ N L h x ≤ (1+ε)*(commonBaseCount M₁ M₂:ℝ) then witnessKernel n hn M₁ M₂ N L h x else 0) theorem real_annealing_success (hE₁ : M₁.E=Set.univ) (hE₂ : M₂.E=Set.univ) (hr : M₁.eRank=M₂.eRank) (ε : ℝ) (hε0 : 0<ε) (hε1 : ε<1) (b : ℕ) (hb : (1/2:ℝ)^b ≤ ε/10) (hZ : 0 (79/100)*(if Good h then 1 else 0)) (fun h => ∑ x,if (1-ε)*(commonBaseCount M₁ M₂:ℝ) ≤ guardedEstimate n M₁ M₂ N L h x ∧ guardedEstimate n M₁ M₂ N L h x ≤ (1+ε)*(commonBaseCount M₁ M₂:ℝ) then witnessKernel n hn M₁ M₂ N L h x else 0) L [] (by intro h hlen have hlen' : h.length=L := by simpa using hlen by_cases hh : Good h · simp only [ite_eq_left hh,mul_one] have he := historyEstimate_accuracy n N hn M₁ M₂ hE₂ hr ε hε0 hε1 b hb hZ h hlen' hh apply (witnessKernel_good_mass n hn M₁ M₂ N hE₁ hE₂ hr ε hε0 hε1 b hb hZ h hlen' hh).trans apply Finset.sum_le_sum intro x _ by_cases hx : Witnessed n M₁ M₂ x · simp only [guardedEstimate,ite_eq_left hx] rw [ite_eq_left he] · simp only [ite_eq_right hx] split_ifs · exact witnessKernel_nonneg n hn M₁ M₂ N L h x · rfl · simp only [ite_eq_right hh,mul_zero] exact Finset.sum_nonneg (fun x _ => by split_ifs · exact witnessKernel_nonneg n hn M₁ M₂ N L h x · rfl)) rw [FiniteExperiment.expect_mul_left] at hmono change 3/4 ≤ actualRealSuccess n hn M₁ M₂ N L ε apply le_trans _ hmono have h := mul_le_mul_of_nonneg_left hmain (by norm_num : (0:ℝ) ≤ 79/100) norm_num at h ⊢ exact le_trans (by norm_num) h end section open scoped BigOperators Classical abbrev BitWord (h : ℕ) := Fin h → Bool def wordEquiv : (h : ℕ) → BitWord h ≃ Fin (2^h) | 0 => { toFun := fun _ => 0 invFun := fun _ => Fin.elim0 left_inv := fun _ => Subsingleton.elim _ _ right_inv := by intro i apply Fin.ext have hi : i.val < 1 := by exact i.isLt change 0=i.val omega } | h+1 => (Fin.consEquiv (fun _ : Fin (h+1) => Bool)).symm |>.trans ((Equiv.prodCongr finTwoEquiv.symm (wordEquiv h)).trans (finProdFinEquiv.trans (finCongr (by rw [pow_succ]; omega : 2*2^h=2^(h+1))))) noncomputable def uniformAverage {X : Type*} [Fintype X] (f : X → ℝ) : ℝ := (∑ x,f x)/(Fintype.card X:ℝ) lemma uniformAverage_equiv {X Y : Type*} [Fintype X] [Fintype Y] (e : X ≃ Y) (f : Y → ℝ) : uniformAverage (fun x => f (e x))=uniformAverage f := by rw [uniformAverage,uniformAverage,e.sum_comp,Fintype.card_congr e] lemma uniformAverage_const {X : Type*} [Fintype X] [Nonempty X] (r : ℝ) : uniformAverage (fun _ : X => r)=r := by have h : (Fintype.card X:ℝ)≠0 := by exact_mod_cast ne_of_gt (Fintype.card_pos) simp [uniformAverage,h] lemma uniformAverage_add {X : Type*} [Fintype X] (f g : X → ℝ) : uniformAverage (fun x => f x+g x)=uniformAverage f+uniformAverage g := by simp [uniformAverage,Finset.sum_add_distrib,add_div] lemma uniformAverage_mul_left {X : Type*} [Fintype X] (r : ℝ) (f : X → ℝ) : uniformAverage (fun x => r*f x)=r*uniformAverage f := by simp [uniformAverage,← Finset.mul_sum,mul_div_assoc] lemma uniformAverage_prod {X Y : Type*} [Fintype X] [Fintype Y] (f : X × Y → ℝ) : uniformAverage f=uniformAverage (fun x => uniformAverage (fun y => f (x,y))) := by simp only [uniformAverage,Fintype.sum_prod_type,Fintype.card_prod,Nat.cast_mul] rw [← Finset.sum_div] ring lemma uniformAverage_fin_succ {X : Type*} [Fintype X] (D : ℕ) (f : (Fin (D+1) → X) → ℝ) : uniformAverage f=uniformAverage (fun x => uniformAverage (fun rest => f (Fin.cons x rest))) := by rw [← uniformAverage_equiv (Fin.consEquiv (fun _ : Fin (D+1) => X)) f,uniformAverage_prod] rfl def boundedUniform (v h : ℕ) : (D : ℕ) → (Fin D → BitWord h) → Option (Fin v) | 0,_ => none | D+1,bits => let x := wordEquiv h (bits 0) if hx : x.val < v then some ⟨x.val,hx⟩ else boundedUniform v h D (Fin.tail bits) noncomputable def rejectionRate (v h : ℕ) : ℝ := (2^h-v:ℕ)/(2:ℝ)^h lemma acceptedCard (v T : ℕ) (hv : v≤T) : Fintype.card {x : Fin T // x.val < v}=v := by let e : {x : Fin T // x.val < v} ≃ Fin v := { toFun := fun x => ⟨x.val.val,x.property⟩ invFun := fun x => ⟨⟨x.val,lt_of_lt_of_le x.isLt hv⟩,x.isLt⟩ left_inv := by intro x; rfl right_inv := by intro x; rfl } simpa using Fintype.card_congr e lemma rejectedCard (v T : ℕ) (hv : v≤T) : Fintype.card {x : Fin T // ¬x.val < v}=T-v := by rw [Fintype.card_subtype_compl,acceptedCard v T hv,Fintype.card_fin] lemma sum_ite_count {X : Type*} [Fintype X] (p : X → Prop) [DecidablePred p] (r : ℝ) : (∑ x,if p x then r else 0)=(Fintype.card {x // p x}:ℝ)*r := by rw [← Finset.sum_filter] simp only [Finset.sum_const,nsmul_eq_mul] congr 1 exact_mod_cast (Fintype.card_subtype p).symm lemma one_trial_none (v h : ℕ) (hv : v≤2^h) (r : ℝ) : uniformAverage (fun bits : BitWord h => if (wordEquiv h bits).val < v then 0 else r)= rejectionRate v h*r := by rw [uniformAverage_equiv (wordEquiv h) (fun x => if x.val simp [hx] _ = _ := by rw [sum_ite_count,rejectedCard _ _ hv] rw [he,Fintype.card_fin,Nat.cast_pow,Nat.cast_ofNat] ring lemma one_trial_some (v h : ℕ) (hv : v≤2^h) (a : Fin v) (r : ℝ) : uniformAverage (fun bits : BitWord h => if hx : (wordEquiv h bits).val if hx : (wordEquiv h bits).val (if wordEquiv h bits=aT then 1 else 0)+ (if (wordEquiv h bits).val if x=aT then 1 else 0)] simp [uniformAverage,aT] lemma boundedUniform_failure (v h D : ℕ) (hv : v≤2^h) : uniformAverage (fun bits => if boundedUniform v h D bits=none then (1:ℝ) else 0)= rejectionRate v h^D := by induction D with | zero => simp [boundedUniform,uniformAverage_const] | succ D ih => rw [uniformAverage_fin_succ] have he : (fun x : BitWord h => uniformAverage (fun rest : Fin D → BitWord h => if boundedUniform v h (D+1) (Fin.cons x rest)=none then (1:ℝ) else 0)) = fun x => if (wordEquiv h x).val if boundedUniform v h D bits=none then (1:ℝ) else 0)≤(1/2:ℝ)^D := by rw [boundedUniform_failure v h D hv] exact pow_le_pow_left₀ (rejectionRate_bounds v h hv hhalf).1 (rejectionRate_bounds v h hv hhalf).2 D lemma clog_trial_size (v : ℕ) (hv : 0 if boundedUniform v h D bits=some a then (1:ℝ) else 0)= (1-rejectionRate v h^D)/(v:ℝ) := by have hv' : (v:ℝ)≠0 := by exact_mod_cast ne_of_gt hv0 have hT : (2:ℝ)^h≠0 := by positivity induction D with | zero => simp [boundedUniform,uniformAverage_const] | succ D ih => rw [uniformAverage_fin_succ] have he : (fun x : BitWord h => uniformAverage (fun rest : Fin D → BitWord h => if boundedUniform v h (D+1) (Fin.cons x rest)=some a then (1:ℝ) else 0)) = fun x => if hx : (wordEquiv h x).val ∑ j,f j x)=∑ j,uniformAverage (f j) := by unfold uniformAverage rw [Finset.sum_comm,Finset.sum_div] lemma boundedUniform_law (v h D : ℕ) (hv : v ≤ 2^h) (hv0 : 0 < v) (φ : Option (Fin v) → ℝ) : uniformAverage (fun bits => φ (boundedUniform v h D bits)) = rejectionRate v h^D*φ none + (1-rejectionRate v h^D)*uniformAverage (fun a => φ (some a)) := by have he : (fun bits => φ (boundedUniform v h D bits)) = fun bits => φ none*(if boundedUniform v h D bits=none then 1 else 0) + ∑ a : Fin v,φ (some a)*(if boundedUniform v h D bits=some a then 1 else 0) := by funext bits cases e : boundedUniform v h D bits with | none => simp | some a => simp rw [he,uniformAverage_add,uniformAverage_mul_left,boundedUniform_failure v h D hv, uniformAverage_sum] simp_rw [uniformAverage_mul_left,boundedUniform_probability v h D hv hv0] rw [← Finset.sum_mul] unfold uniformAverage rw [Fintype.card_fin] ring lemma uniformAverage_nonneg {X : Type*} [Fintype X] (f : X → ℝ) (hf : ∀ x,0≤f x) : 0≤uniformAverage f := by exact div_nonneg (Finset.sum_nonneg (fun x _ => hf x)) (Nat.cast_nonneg _) lemma uniformAverage_mono {X : Type*} [Fintype X] (f g : X → ℝ) (hfg : ∀ x,f x≤g x) : uniformAverage f≤uniformAverage g := by exact div_le_div_of_nonneg_right (Finset.sum_le_sum (fun x _ => hfg x)) (Nat.cast_nonneg _) lemma uniformAverage_sub_const {X : Type*} [Fintype X] [Nonempty X] (f : X → ℝ) (r : ℝ) : uniformAverage (fun x => f x-r)=uniformAverage f-r := by unfold uniformAverage rw [Finset.sum_sub_distrib,sub_div] simp only [Finset.sum_const,Finset.card_univ,nsmul_eq_mul] have h : (Fintype.card X:ℝ)≠0 := by exact_mod_cast ne_of_gt (Fintype.card_pos) field_simp def bitPrefix (h H : ℕ) (hh : h≤H) (w : BitWord H) : BitWord h := fun i => w ⟨i.val,lt_of_lt_of_le i.isLt hh⟩ lemma uniformAverage_bitPrefix (h H : ℕ) (hh : h≤H) (φ : BitWord h → ℝ) : uniformAverage (fun w => φ (bitPrefix h H hh w))=uniformAverage φ := by obtain ⟨t,rfl⟩ := Nat.exists_eq_add_of_le hh rw [← uniformAverage_equiv (Fin.appendEquiv h t) (fun w => φ (bitPrefix h (h+t) hh w)),uniformAverage_prod] have he : ∀ a : BitWord h,∀ b : BitWord t,bitPrefix h (h+t) hh ((Fin.appendEquiv h t) (a,b))=a := by intro a b funext i change Fin.append a b (Fin.castAdd t i)=a i simp simp_rw [he,uniformAverage_const] lemma uniformAverage_prefixTrials (h H D : ℕ) (hh : h≤H) (φ : (Fin D → BitWord h) → ℝ) : uniformAverage (fun w : Fin D → BitWord H => φ (fun d => bitPrefix h H hh (w d)))=uniformAverage φ := by induction D with | zero => have he : ∀ w : Fin 0 → BitWord H,(fun d => bitPrefix h H hh (w d))=(fun d : Fin 0 => Fin.elim0 d) := by intro w; funext d; exact Fin.elim0 d have hf : ∀ w : Fin 0 → BitWord h,w=(fun d : Fin 0 => Fin.elim0 d) := by intro w; funext d; exact Fin.elim0 d simp_rw [he] rw [uniformAverage_const] conv_rhs => arg 1; ext w; rw [hf w] rw [uniformAverage_const] | succ D ih => rw [uniformAverage_fin_succ,uniformAverage_fin_succ] have he : ∀ x : BitWord H,∀ xs : Fin D → BitWord H, (fun d : Fin (D+1) => bitPrefix h H hh ((Fin.cons x xs : Fin (D+1) → BitWord H) d))= Fin.cons (bitPrefix h H hh x) (fun d => bitPrefix h H hh (xs d)) := by intro x xs; funext d; refine Fin.cases ?_ (fun i => ?_) d <;> rfl simp_rw [he] have hhφ : ∀ x : BitWord H, uniformAverage (fun xs : Fin D → BitWord H => φ (Fin.cons (bitPrefix h H hh x) (fun d => bitPrefix h H hh (xs d))))= uniformAverage (fun xs : Fin D → BitWord h => φ (Fin.cons (bitPrefix h H hh x) xs)) := by intro x exact ih (fun xs => φ (Fin.cons (bitPrefix h H hh x) xs)) simp_rw [hhφ] exact uniformAverage_bitPrefix h H hh (fun x => uniformAverage (fun xs => φ (Fin.cons x xs))) inductive DrawTree (A : Type*) where | leaf (a : A) | draw (v : ℕ) (next : Fin (v+1) → DrawTree A) namespace DrawTree section open scoped BigOperators Classical variable {A : Type*} noncomputable def expectation (φ : A → ℝ) : DrawTree A → ℝ | .leaf a => φ a | .draw _ k => uniformAverage (fun i => expectation φ (k i)) lemma expectation_nonneg (φ : A → ℝ) (hφ : ∀ a,0≤φ a) (t : DrawTree A) : 0≤t.expectation φ := by induction t with | leaf a => exact hφ a | draw v k ih => exact uniformAverage_nonneg _ ih lemma expectation_le_one (φ : A → ℝ) (hφ : ∀ a,φ a≤1) (t : DrawTree A) : t.expectation φ≤1 := by induction t with | leaf a => exact hφ a | draw v k ih => have h := uniformAverage_mono _ (fun _ : Fin (v+1) => 1) ih simpa only [expectation,uniformAverage_const] using h def Fits (H : ℕ) : ℕ → DrawTree A → Prop | _,.leaf _ => True | 0,.draw _ _ => False | M+1,.draw v k => Nat.clog 2 (v+1)≤H ∧ ∀ i,Fits H M (k i) def run (H D : ℕ) : (M : ℕ) → DrawTree A → (Fin M → Fin D → BitWord H) → Option A | _,.leaf a,_ => some a | 0,.draw _ _,_ => none | M+1,.draw v k,bits => if hh : Nat.clog 2 (v+1)≤H then match boundedUniform (v+1) (Nat.clog 2 (v+1)) D (fun d => bitPrefix _ H hh (bits 0 d)) with | none => none | some a => run H D M (k a) (Fin.tail bits) else none def optionValue (φ : A → ℝ) : Option A → ℝ | none => 0 | some a => φ a lemma run_draw_average (H D M v : ℕ) (k : Fin (v+1) → DrawTree A) (hh : Nat.clog 2 (v+1)≤H) (φ : A → ℝ) : uniformAverage (fun bits => optionValue φ (run H D (M+1) (.draw v k) bits))= (1-rejectionRate (v+1) (Nat.clog 2 (v+1))^D)* uniformAverage (fun a : Fin (v+1) => uniformAverage (fun rest => optionValue φ (run H D M (k a) rest))) := by rw [uniformAverage_fin_succ] simp only [run,dite_eq_left hh,Fin.cons_zero,Fin.tail_cons] let ψ : Option (Fin (v+1)) → ℝ := fun z => match z with | none => 0 | some a => uniformAverage (fun rest => optionValue φ (run H D M (k a) rest)) have he : (fun x : Fin D → BitWord H => uniformAverage (fun rest : Fin M → Fin D → BitWord H => optionValue φ (match boundedUniform (v+1) (Nat.clog 2 (v+1)) D (fun d => bitPrefix _ H hh (x d)) with | none => none | some a => run H D M (k a) rest))) = fun x => ψ (boundedUniform (v+1) (Nat.clog 2 (v+1)) D (fun d => bitPrefix _ H hh (x d))) := by funext x cases hz : boundedUniform (v+1) (Nat.clog 2 (v+1)) D (fun d => bitPrefix _ H hh (x d)) with | none => exact uniformAverage_const 0 | some a => rfl rw [he,uniformAverage_prefixTrials _ _ D hh (fun w => ψ (boundedUniform (v+1) (Nat.clog 2 (v+1)) D w))] rw [boundedUniform_law _ _ _ (clog_trial_size _ (by omega)).1 (by omega)] simp only [ψ,mul_zero,zero_add] theorem run_lower (H D M : ℕ) (t : DrawTree A) (ht : Fits H M t) (φ : A → ℝ) (_ : ∀ a,0≤φ a) (hφ1 : ∀ a,φ a≤1) : t.expectation φ-(M:ℝ)*(1/2:ℝ)^D ≤ uniformAverage (fun bits => optionValue φ (run H D M t bits)) := by induction M generalizing t with | zero => cases t with | leaf a => simp [run,optionValue,expectation,uniformAverage_const] | draw v k => exact False.elim ht | succ M ih => cases t with | leaf a => simp only [expectation,run,optionValue,uniformAverage_const] have h : 0 ≤ ((M+1:ℕ):ℝ)*(1/2:ℝ)^D := by positivity linarith | draw v k => obtain ⟨hh,hk⟩ := ht rw [run_draw_average H D M v k hh φ] have hlocal := uniformAverage_mono (fun a => (k a).expectation φ-(M:ℝ)*(1/2:ℝ)^D) (fun a => uniformAverage (fun bits => optionValue φ (run H D M (k a) bits))) (fun a => ih (k a) (hk a)) rw [uniformAverage_sub_const] at hlocal let r := rejectionRate (v+1) (Nat.clog 2 (v+1))^D have hb := rejectionRate_bounds (v+1) (Nat.clog 2 (v+1)) (clog_trial_size _ (by omega)).1 (clog_trial_size _ (by omega)).2 have hr0 : 0≤r := pow_nonneg hb.1 D have hr : r≤(1/2:ℝ)^D := pow_le_pow_left₀ hb.1 hb.2 D have hr1 : r≤1 := hr.trans (pow_le_one₀ (by norm_num) (by norm_num)) have hE : uniformAverage (fun a => (k a).expectation φ)≤1 := expectation_le_one φ hφ1 (.draw v k) have hmul := mul_le_mul_of_nonneg_left hlocal (sub_nonneg.mpr hr1) have hz : 0≤(M:ℝ)*(1/2:ℝ)^D := by positivity change _ ≤ (1-r)*_ change uniformAverage (fun a => (k a).expectation φ)-((M+1:ℕ):ℝ)*(1/2:ℝ)^D ≤ _ push_cast nlinarith [mul_nonneg hr0 hz,mul_nonneg hr0 (sub_nonneg.mpr hE)] end open scoped BigOperators Classical variable {A B : Type*} def bind : DrawTree A → (A → DrawTree B) → DrawTree B | .leaf a,k => k a | .draw v f,k => .draw v (fun i => (f i).bind k) def map (f : A → B) (t : DrawTree A) : DrawTree B := t.bind (fun a => .leaf (f a)) lemma expectation_bind (t : DrawTree A) (k : A → DrawTree B) (φ : B → ℝ) : (t.bind k).expectation φ=t.expectation (fun a => (k a).expectation φ) := by induction t with | leaf a => rfl | draw v f ih => simp only [bind,expectation,ih] lemma expectation_map (t : DrawTree A) (f : A → B) (φ : B → ℝ) : (t.map f).expectation φ=t.expectation (fun a => φ (f a)) := by rw [map,expectation_bind]; rfl lemma fits_mono_steps (H M M' : ℕ) (hM : M≤M') (t : DrawTree A) (ht : Fits H M t) : Fits H M' t := by induction M generalizing M' t with | zero => cases t <;> simp_all [Fits] | succ M ih => cases t with | leaf a => simp [Fits] | draw v f => cases M' with | zero => omega | succ M' => exact ⟨ht.1,fun i => ih M' (by omega) (f i) (ht.2 i)⟩ lemma fits_bind (H M N : ℕ) (t : DrawTree A) (k : A → DrawTree B) (ht : Fits H M t) (hk : ∀ a,Fits H N (k a)) : Fits H (M+N) (t.bind k) := by induction M generalizing t with | zero => cases t with | leaf a => simpa only [bind,Nat.zero_add] using hk a | draw v f => exact False.elim ht | succ M ih => cases t with | leaf a => exact fits_mono_steps H N (M+1+N) (by omega) (k a) (hk a) | draw v f => have he : M+1+N=(M+N)+1 := by omega rw [he] exact ⟨ht.1,fun i => ih (f i) (ht.2 i)⟩ def rationalCoin (a v : ℕ) : DrawTree Bool := .draw v (fun i => .leaf (decide (i.val φ (decide (i.val φ (decide (i.val φ false+if i.val simp [h] rw [he,uniformAverage_add,uniformAverage_const] unfold uniformAverage rw [sum_ite_count,acceptedCard a (v+1) ha,Fintype.card_fin] have hv : ((v+1:ℕ):ℝ)≠0 := by positivity field_simp ; ring lemma rationalCoin_fits (a v H : ℕ) (hh : Nat.clog 2 (v+1)≤H) : Fits H 1 (rationalCoin a v) := ⟨hh,fun _ => trivial⟩ def bernoulli (p : ℚ) : DrawTree Bool := rationalCoin p.num.natAbs (p.den-1) lemma bernoulli_expectation (p : ℚ) (hp0 : 0≤p) (hp1 : p≤1) (φ : Bool → ℝ) : (bernoulli p).expectation φ=(p:ℝ)*φ true+(1-(p:ℝ))*φ false := by have hd : p.den-1+1=p.den := by have h := p.den_pos; omega have hn : (p.num.natAbs:ℤ)=p.num := Int.natAbs_of_nonneg (Rat.num_nonneg.mpr hp0) have hnr : (p.num.natAbs:ℝ)=(p.num:ℝ) := by simpa only [Int.cast_natCast] using congrArg (fun z : ℤ => (z:ℝ)) hn have he : (p.num.natAbs:ℝ)/(p.den:ℝ)=(p:ℝ) := by rw [hnr,Rat.cast_def] have ha : p.num.natAbs≤p.den := by have hd' : (0:ℝ) hn rfl⟩ intro he exact a.2.property (he ▸ a.1.property) omit sectionInstance110 sectionInstance111 in lemma exchangedSet_right_difference [Fintype Γ] [DecidableEq Γ] (S : Set Γ) (a : ExchangeChoice S) : exchangedSet S a\S={a.2.val} := by ext x simp only [exchangedSet,Set.mem_sdiff,Set.mem_insert_iff,Set.mem_singleton_iff] constructor · rintro ⟨hh,hn⟩ exact hh.resolve_right (fun h => hn h.1) · intro he; subst x exact ⟨Or.inl rfl,a.2.property⟩ lemma exchangedSet_injective (S : Set Γ) : Function.Injective (exchangedSet S) := by intro a b he apply Prod.ext · apply Subtype.ext have h := congrArg (fun T => S\T) he rw [exchangedSet_left_difference,exchangedSet_left_difference] at h exact Set.singleton_injective h · apply Subtype.ext have h := congrArg (fun T => T\S) he rw [exchangedSet_right_difference,exchangedSet_right_difference] at h exact Set.singleton_injective h lemma exchangedSet_exists_iff (S T : Set Γ) : (∃ a : ExchangeChoice S,exchangedSet S a=T) ↔ ExchangeAdjacent S T := by constructor · rintro ⟨a,rfl⟩; exact exchangedSet_adjacent S a · intro h obtain ⟨a,ha,b,hb,he⟩ := h.move exact ⟨(⟨a,ha⟩,⟨b,hb⟩),he.symm⟩ lemma sum_exchangedSet_indicator (S T : Set Γ) (r : ℝ) : (∑ a : ExchangeChoice S,if exchangedSet S a=T then r else 0)= if ExchangeAdjacent S T then r else 0 := by by_cases h : ExchangeAdjacent S T · obtain ⟨a,ha⟩ := (exchangedSet_exists_iff S T).mpr h have he : ∀ b : ExchangeChoice S,exchangedSet S b=T ↔ b=a := by intro b; rw [←ha]; exact (exchangedSet_injective S).eq_iff simp [he,h] · have he : ∀ a : ExchangeChoice S, exchangedSet S a≠T := by intro a ha; exact h ((exchangedSet_exists_iff S T).mp ⟨a,ha⟩) simp [he,h] lemma exchangeChoice_card (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hcover : pairSupport gs=Set.univ) (S : ChainIndex gs) : Fintype.card (ExchangeChoice S.val)=gs.length^2 := by rw [Fintype.card_prod] have hs : Fintype.card S.val=S.val.ncard := by rw [Set.ncard_eq_toFinset_card',Set.toFinset_card] have hc : Fintype.card ↥(S.valᶜ)=S.valᶜ.ncard := by rw [Set.ncard_eq_toFinset_card',Set.toFinset_card] rw [hs,hc] have ht := S.val.ncard_add_ncard_compl rw [Nat.card_eq_fintype_card,slots_ground_card gs hgs hcover,S.property.ncard hgs hcover] at ht have hh : S.valᶜ.ncard=gs.length := by omega rw [S.property.ncard hgs hcover,hh,pow_two] noncomputable def metropolisAcceptance (gs : List (Γ × Γ)) (w : (Γ × Γ) → (Γ × Γ) → ℝ) (f : Set Γ → ℝ) (S T : ChainIndex gs) : ℝ := min 1 (chainWeight gs w f T.val/chainWeight gs w f S.val) noncomputable def exchangeOffer (gs : List (Γ × Γ)) (w : (Γ × Γ) → (Γ × Γ) → ℝ) (f : Set Γ → ℝ) (S : ChainIndex gs) (a : ExchangeChoice S.val) (φ : ChainIndex gs → ℝ) : ℝ := if ht : ChainState gs (exchangedSet S.val a) then let T : ChainIndex gs := ⟨exchangedSet S.val a,ht⟩ metropolisAcceptance gs w f S T*φ T+(1-metropolisAcceptance gs w f S T)*φ S else φ S omit sectionInstance111 in lemma exchangeOffer_expansion [DecidableEq Γ] (gs : List (Γ × Γ)) (w : (Γ × Γ) → (Γ × Γ) → ℝ) (f : Set Γ → ℝ) (S : ChainIndex gs) (a : ExchangeChoice S.val) (φ : ChainIndex gs → ℝ) : exchangeOffer gs w f S a φ=φ S+∑ T : ChainIndex gs, if exchangedSet S.val a=T.val then metropolisAcceptance gs w f S T*(φ T-φ S) else 0 := by unfold exchangeOffer split_ifs with ht · let T : ChainIndex gs := ⟨exchangedSet S.val a,ht⟩ have he : ∀ U : ChainIndex gs,exchangedSet S.val a=U.val ↔ U=T := by intro U constructor · intro he; exact Subtype.ext he.symm · intro he; subst U; rfl simp only [he,Finset.sum_ite_eq',Finset.mem_univ,ite_true] change _=φ S+metropolisAcceptance gs w f S T*(φ T-φ S) ring · have he : ∀ T : ChainIndex gs,exchangedSet S.val a≠T.val := by intro T he; exact ht (he ▸ T.property) simp [he] lemma metropolisAcceptance_min (gs : List (Γ × Γ)) (w : (Γ × Γ) → (Γ × Γ) → ℝ) (f : Set Γ → ℝ) (hw : ∀ p r,0 exchangeOffer gs w f S a φ))/2= (metropolisChain gs hgs hne hcover w f hw hf).apply φ S := by have hn : (gs.length:ℝ)≠0 := by exact_mod_cast ne_of_gt (List.length_pos_iff.mpr hne) have hc : (Fintype.card (ExchangeChoice S.val):ℝ)=(gs.length:ℝ)^2 := by rw [exchangeChoice_card gs hgs hcover S,Nat.cast_pow] have hex : uniformAverage (fun a => exchangeOffer gs w f S a φ)= φ S+(∑ T : ChainIndex gs,if ExchangeAdjacent S.val T.val then metropolisAcceptance gs w f S T*(φ T-φ S) else 0)/(gs.length:ℝ)^2 := by simp_rw [exchangeOffer_expansion] rw [uniformAverage_add] have hnon : Nonempty (ExchangeChoice S.val) := Fintype.card_pos_iff.mp (by rw [exchangeChoice_card gs hgs hcover S] exact pow_pos (List.length_pos_iff.mpr hne) _) let := hnon rw [uniformAverage_const] congr 1 unfold uniformAverage rw [hc,Finset.sum_comm] simp_rw [sum_exchangedSet_indicator] rw [hex] change _=∑ T,(metropolisMove gs w f S T+if S=T then 1-∑ U,metropolisMove gs w f S U else 0)*φ T simp_rw [add_mul,ite_mul,zero_mul] rw [Finset.sum_add_distrib] simp only [Finset.sum_ite_eq,Finset.mem_univ,ite_true] have he : (∑ T : ChainIndex gs,if ExchangeAdjacent S.val T.val then metropolisAcceptance gs w f S T*(φ T-φ S) else 0)/(gs.length:ℝ)^2/2= ∑ T : ChainIndex gs,metropolisMove gs w f S T*(φ T-φ S) := by rw [Finset.sum_div,Finset.sum_div] apply Finset.sum_congr rfl intro T _ by_cases ht : ExchangeAdjacent S.val T.val · simp only [metropolisMove,ite_eq_left ht,metropolisAcceptance_min gs w f hw hf] field_simp · simp [metropolisMove,ht] have hsum : (∑ T : ChainIndex gs,metropolisMove gs w f S T*(φ T-φ S))= (∑ T : ChainIndex gs,metropolisMove gs w f S T*φ T)- (∑ T : ChainIndex gs,metropolisMove gs w f S T)*φ S := by simp [mul_sub,Finset.sum_sub_distrib,Finset.sum_mul] linarith end MetropolisSampling section RationalSampling open scoped BigOperators Classical variable {Γ : Type*} [sectionInstance112 : Fintype Γ] [sectionInstance113 : DecidableEq Γ] noncomputable def rationalMultiplier (gs : List (Γ × Γ)) (w : (Γ × Γ) → (Γ × Γ) → ℚ) (S : Set Γ) : ℚ := if h : ∃ p r,DefectState gs p r S then w h.choose h.choose_spec.choose else 1 noncomputable def rationalWeight (gs : List (Γ × Γ)) (w : (Γ × Γ) → (Γ × Γ) → ℚ) (f : Set Γ → ℚ) (S : Set Γ) : ℚ := rationalMultiplier gs w S*f S omit sectionInstance113 in lemma rationalMultiplier_cast [DecidableEq Γ] (gs : List (Γ × Γ)) (w : (Γ × Γ) → (Γ × Γ) → ℚ) (S : Set Γ) : (rationalMultiplier gs w S:ℝ)=chainMultiplier gs (fun p r => (w p r:ℝ)) S := by unfold rationalMultiplier chainMultiplier split_ifs <;> simp lemma rationalWeight_cast (gs : List (Γ × Γ)) (w : (Γ × Γ) → (Γ × Γ) → ℚ) (f : Set Γ → ℚ) (S : Set Γ) : (rationalWeight gs w f S:ℝ)=chainWeight gs (fun p r => (w p r:ℝ)) (fun S => (f S:ℝ)) S := by simp [rationalWeight,chainWeight,rationalMultiplier_cast] noncomputable def rationalEmpirical (H : Set Γ → ℚ) (l : List (Set Γ)) : ℚ := (l.map H).sum/(l.length:ℚ) omit sectionInstance112 sectionInstance113 in lemma rationalEmpirical_cast [Fintype Γ] [DecidableEq Γ] (H : Set Γ → ℚ) (l : List (Set Γ)) : (rationalEmpirical H l:ℝ)=empirical (fun S => (H S:ℝ)) l := by simp [rationalEmpirical,empirical,Rat.cast_list_sum,List.map_map,Function.comp_def] noncomputable def rationalPlain (gs : List (Γ × Γ)) (g : Set Γ → ℚ) (S : Set Γ) : ℚ := if PlainState gs S then g S else 0 omit sectionInstance112 sectionInstance113 in lemma rationalPlain_cast [Fintype Γ] [DecidableEq Γ] (gs : List (Γ × Γ)) (g : Set Γ → ℚ) (S : Set Γ) : (rationalPlain gs g S:ℝ)=plainObservable gs (fun S => (g S:ℝ)) S := by unfold rationalPlain plainObservable; split_ifs <;> simp noncomputable def rationalDefect (gs : List (Γ × Γ)) (p r : Γ × Γ) (S : Set Γ) : ℚ := if DefectState gs p r S then 1 else 0 omit sectionInstance112 sectionInstance113 in lemma rationalDefect_cast [Fintype Γ] [DecidableEq Γ] (gs : List (Γ × Γ)) (p r : Γ × Γ) (S : Set Γ) : (rationalDefect gs p r S:ℝ)=defectIndicator gs p r S := by unfold rationalDefect defectIndicator; split_ifs <;> simp noncomputable def rationalLearn (gs : List (Γ × Γ)) (w : (Γ × Γ) → (Γ × Γ) → ℚ) (l : List (Set Γ)) (p r : Γ × Γ) : ℚ := if p∈gs ∧ r∈gs ∧ p≠r then w p r*(rationalEmpirical (rationalPlain gs (fun _ => 1)) l/rationalEmpirical (rationalDefect gs p r) l) else w p r lemma rationalLearn_cast (gs : List (Γ × Γ)) (w : (Γ × Γ) → (Γ × Γ) → ℚ) (l : List (Set Γ)) (p r : Γ × Γ) : (rationalLearn gs w l p r:ℝ)=learnedMultipliers gs (fun p r => (w p r:ℝ)) l p r := by unfold rationalLearn learnedMultipliers split_ifs <;> simp [rationalEmpirical_cast,rationalPlain_cast,rationalDefect_cast] noncomputable def rationalHistory {X : Type*} (gs : List (Γ × Γ)) (sample : X → List (Set Γ)) (h : List X) : (Γ × Γ) → (Γ × Γ) → ℚ := h.foldl (fun w x => rationalLearn gs w (sample x)) (fun _ _ => 4) lemma rationalHistory_cast {X : Type*} (gs : List (Γ × Γ)) (sample : X → List (Set Γ)) (h : List X) (p r : Γ × Γ) : (rationalHistory gs sample h p r:ℝ)=historyWeights gs sample h p r := by induction h using List.reverseRecOn generalizing p r with | nil => norm_num [rationalHistory,historyWeights] | append_singleton h x ih => simp only [rationalHistory,List.foldl_append,List.foldl_cons,List.foldl_nil,historyWeights_snoc] rw [rationalLearn_cast] have he : (fun p r => ((h.foldl (fun w x => rationalLearn gs w (sample x)) (fun _ _ => 4)) p r:ℝ))= historyWeights gs sample h := by funext p r; exact ih p r rw [he] def rationalRho (n : ℕ) : ℚ := 1-1/(2*(n:ℚ)) lemma rationalRho_cast (n : ℕ) : (rationalRho n:ℝ)=annealRho n := by simp [rationalRho,annealRho] noncomputable def rationalAnneal (M : Matroid Γ) (n j : ℕ) (S : Set Γ) : ℚ := (rationalRho n^j)^(n-(M.eRk S).toNat) omit sectionInstance112 sectionInstance113 in lemma rationalAnneal_cast [Fintype Γ] [DecidableEq Γ] (M : Matroid Γ) (n j : ℕ) (S : Set Γ) : (rationalAnneal M n j S:ℝ)=annealWeight M n j S := by simp [rationalAnneal,annealWeight,matroidWeight,rationalRho_cast] noncomputable def rationalRatio (gs : List (Γ × Γ)) (g : Set Γ → ℚ) (l : List (Set Γ)) : ℚ := rationalEmpirical (rationalPlain gs g) l / rationalEmpirical (rationalPlain gs (fun _ => 1)) l lemma rationalRatio_cast (gs : List (Γ × Γ)) (g : Set Γ → ℚ) (l : List (Set Γ)) : (rationalRatio gs g l:ℝ)=empiricalRatio gs (fun S => (g S:ℝ)) l := by simp [rationalRatio,empiricalRatio,rationalEmpirical_cast,rationalPlain_cast] end RationalSampling namespace DrawTree open scoped BigOperators Classical noncomputable def uniformChoice (A : Type*) [Fintype A] [Nonempty A] : DrawTree A := let h : Fintype.card A-1+1=Fintype.card A := by have hh := Fintype.card_pos (α := A); omega .draw (Fintype.card A-1) (fun i => .leaf ((Fintype.equivFin A).symm (Fin.cast h i))) lemma uniformChoice_expectation (A : Type*) [Fintype A] [Nonempty A] (φ : A → ℝ) : (uniformChoice A).expectation φ=uniformAverage φ := by unfold uniformChoice change uniformAverage (fun i => φ ((Fintype.equivFin A).symm (Fin.cast _ i)))=_ exact uniformAverage_equiv ((finCongr (by have hh := Fintype.card_pos (α := A); omega)).trans (Fintype.equivFin A).symm) φ lemma uniformChoice_fits (A : Type*) [Fintype A] [Nonempty A] (H : ℕ) (h : Nat.clog 2 (Fintype.card A)≤H) : Fits H 1 (uniformChoice A) := by unfold uniformChoice refine ⟨?_,fun _ => trivial⟩ have he : Fintype.card A-1+1=Fintype.card A := by have hh := Fintype.card_pos (α := A); omega simpa only [he] using h end DrawTree section RationalMetropolis open scoped BigOperators Classical variable {Γ : Type*} [Fintype Γ] [sectionInstance115 : DecidableEq Γ] variable (gs : List (Γ × Γ)) noncomputable def rationalAcceptance (w : (Γ × Γ) → (Γ × Γ) → ℚ) (f : Set Γ → ℚ) (S T : ChainIndex gs) : ℚ := min 1 (rationalWeight gs w f T.val/rationalWeight gs w f S.val) lemma rationalAcceptance_cast (w : (Γ × Γ) → (Γ × Γ) → ℚ) (f : Set Γ → ℚ) (S T : ChainIndex gs) : (rationalAcceptance gs w f S T:ℝ)=metropolisAcceptance gs (fun p r => (w p r:ℝ)) (fun S => (f S:ℝ)) S T := by simp [rationalAcceptance,metropolisAcceptance,rationalWeight_cast] omit sectionInstance115 in lemma rationalAcceptance_bounds [DecidableEq Γ] (w : (Γ × Γ) → (Γ × Γ) → ℚ) (f : Set Γ → ℚ) (hw : ∀ p r,00 := by intro S unfold rationalWeight rationalMultiplier apply mul_pos _ (hf S) split_ifs <;> first | exact hw _ _ | norm_num exact ⟨le_min (by norm_num) (div_nonneg (hpos _).le (hpos _).le),min_le_left _ _⟩ noncomputable def rationalExchange (w : (Γ × Γ) → (Γ × Γ) → ℚ) (f : Set Γ → ℚ) (S : ChainIndex gs) (a : ExchangeChoice S.val) : DrawTree (ChainIndex gs) := if ht : ChainState gs (exchangedSet S.val a) then let T : ChainIndex gs := ⟨exchangedSet S.val a,ht⟩ (DrawTree.bernoulli (rationalAcceptance gs w f S T)).map (fun accept => if accept then T else S) else .leaf S lemma rationalExchange_expectation (w : (Γ × Γ) → (Γ × Γ) → ℚ) (f : Set Γ → ℚ) (hw : ∀ p r,0 (w p r:ℝ)) (fun S => (f S:ℝ)) S a φ := by unfold rationalExchange exchangeOffer split_ifs with ht · rw [DrawTree.expectation_map,DrawTree.bernoulli_expectation _ (rationalAcceptance_bounds gs w f hw hf S _).1 (rationalAcceptance_bounds gs w f hw hf S _).2] simp only [ite_true,Bool.false_eq_true,ite_false,rationalAcceptance_cast] · rfl noncomputable def rationalMetropolis (hgs : SlotsFresh gs ∅) (hne : gs≠[]) (hcover : pairSupport gs=Set.univ) (w : (Γ × Γ) → (Γ × Γ) → ℚ) (f : Set Γ → ℚ) (S : ChainIndex gs) : DrawTree (ChainIndex gs) := letI : Nonempty (ExchangeChoice S.val) := Fintype.card_pos_iff.mp (by rw [exchangeChoice_card gs hgs hcover S]; exact pow_pos (List.length_pos_iff.mpr hne) _) (DrawTree.bernoulli (1/2)).bind (fun lazy => if lazy then .leaf S else (DrawTree.uniformChoice (ExchangeChoice S.val)).bind (rationalExchange gs w f S)) lemma rationalMetropolis_expectation (hgs : SlotsFresh gs ∅) (hne : gs≠[]) (hcover : pairSupport gs=Set.univ) (w : (Γ × Γ) → (Γ × Γ) → ℚ) (f : Set Γ → ℚ) (hw : ∀ p r,0 (w p r:ℝ)) (fun S => (f S:ℝ)) (by intro p r; exact_mod_cast hw p r) (by intro S; exact_mod_cast hf S)).apply φ S := by unfold rationalMetropolis rw [DrawTree.expectation_bind,DrawTree.bernoulli_expectation _ (by norm_num) (by norm_num)] simp only [ite_true,Bool.false_eq_true,ite_false,DrawTree.expectation, DrawTree.expectation_bind,DrawTree.uniformChoice_expectation, rationalExchange_expectation gs w f hw hf] have he := lazy_exchange_expectation gs hgs hne hcover (fun p r => (w p r:ℝ)) (fun S => (f S:ℝ)) (by intro p r; exact_mod_cast hw p r) (by intro S; exact_mod_cast hf S) S φ rw [←he] norm_num ring end RationalMetropolis namespace DrawTree open scoped BigOperators Classical variable {A B D : Type*} def optionBind (t : DrawTree (Option A)) (k : A → DrawTree (Option B)) : DrawTree (Option B) := t.bind (fun z => match z with | none => .leaf none | some a => k a) def pureSome (a : A) : DrawTree (Option A) := .leaf (some a) lemma expectation_zero (t : DrawTree A) : t.expectation (fun _ => (0:ℝ))=0 := by induction t with | leaf a => rfl | draw v f ih => simp only [expectation,ih,uniformAverage_const] lemma expectation_add (t : DrawTree A) (φ ψ : A → ℝ) : t.expectation (fun a => φ a+ψ a)=t.expectation φ+t.expectation ψ := by induction t with | leaf a => rfl | draw v f ih => simp only [expectation,ih,uniformAverage_add] lemma expectation_mul_left (t : DrawTree A) (c : ℝ) (φ : A → ℝ) : t.expectation (fun a => c*φ a)=c*t.expectation φ := by induction t with | leaf a => rfl | draw v f ih => simp only [expectation,ih,uniformAverage_mul_left] lemma expectation_sum (t : DrawTree A) {J : Type*} (s : Finset J) (φ : J → A → ℝ) : t.expectation (fun a => ∑ j ∈ s,φ j a)=∑ j ∈ s,t.expectation (φ j) := by induction s using Finset.induction_on with | empty => simp only [Finset.sum_empty,expectation_zero] | @insert j s hj ih => simp only [Finset.sum_insert hj,expectation_add,ih] lemma expectation_mono (t : DrawTree A) (φ ψ : A → ℝ) (h : ∀ a,φ a≤ψ a) : t.expectation φ≤t.expectation ψ := by induction t with | leaf a => exact h a | draw v f ih => exact uniformAverage_mono _ _ ih lemma expectation_optionBind (t : DrawTree (Option A)) (k : A → DrawTree (Option B)) (φ : B → ℝ) : (t.optionBind k).expectation (optionValue φ)= t.expectation (optionValue (fun a => (k a).expectation (optionValue φ))) := by rw [optionBind,expectation_bind] congr 1; funext a; cases a <;> rfl lemma optionBind_fits (t : DrawTree (Option A)) (k : A → DrawTree (Option B)) (H M N : ℕ) (ht : Fits H M t) (hk : ∀ a,Fits H N (k a)) : Fits H (M+N) (t.optionBind k) := by apply fits_bind H M N t _ ht intro a; cases a with | none => cases N <;> trivial | some a => exact hk a def Matches [Fintype B] (t : A → DrawTree (Option B)) (P : A → B → ℝ) : Prop := ∀ a φ,(t a).expectation (optionValue φ)=∑ b,P a b*φ b lemma matches_comp [Fintype A] [Fintype B] [Fintype D] (t : A → DrawTree (Option B)) (u : B → DrawTree (Option D)) (P : A → B → ℝ) (Q : B → D → ℝ) (ht : Matches t P) (hu : Matches u Q) : Matches (fun a => (t a).optionBind u) (fun a d => ∑ b,P a b*Q b d) := by intro a φ rw [expectation_optionBind,ht] simp_rw [show ∀ b,(u b).expectation (optionValue φ)=∑ d,Q b d*φ d from fun b => hu b φ] simp only [Finset.mul_sum,Finset.sum_mul,mul_assoc] exact Finset.sum_comm def iterate (t : A → DrawTree (Option A)) : ℕ → A → DrawTree (Option A) | 0,a => pureSome a | k+1,a => (iterate t k a).optionBind t lemma iterate_matches [Fintype A] (t : A → DrawTree (Option A)) (K : FiniteKernel A A) (ht : Matches t K.P) (k : ℕ) : Matches (iterate t k) (K.power k).P := by induction k with | zero => intro a φ change φ a=∑ b,(if a=b then (1:ℝ) else 0)*φ b simp | succ k ih => have h := matches_comp (iterate t k) t (K.power k).P K.P ih ht simpa only [iterate,FiniteKernel.power,FiniteKernel.comp] using h lemma iterate_fits (t : A → DrawTree (Option A)) (H M k : ℕ) (ht : ∀ a,Fits H M (t a)) : ∀ a,Fits H (M*k) (iterate t k a) := by induction k with | zero => intro a; trivial | succ k ih => intro a have h := optionBind_fits (iterate t k a) t H (M*k) M (ih a) ht simpa only [iterate,Nat.mul_succ] using h end DrawTree section DrawHitting open scoped BigOperators Classical variable {X : Type*} [sectionInstance116 : Fintype X] variable (step : X → DrawTree X) (A : X → Prop) noncomputable def hittingTree : ℕ → X → DrawTree (Option (FiniteChain.Inside A)) | 0,_ => .leaf none | k+1,x => (step x).bind (fun y => if hy : A y then .leaf (some ⟨y,hy⟩) else hittingTree k y) omit sectionInstance116 in lemma hittingTree_fits [Fintype X] (H M k : ℕ) (hs : ∀ x,DrawTree.Fits H M (step x)) : ∀ x,DrawTree.Fits H (M*k) (hittingTree step A k x) := by induction k with | zero => intro x; trivial | succ k ih => intro x unfold hittingTree have h := DrawTree.fits_bind H M (M*k) (step x) (fun y => if hy : A y then DrawTree.leaf (some (⟨y,hy⟩ : FiniteChain.Inside A)) else hittingTree step A k y) (hs x) (by intro y; split_ifs; exacts [by cases M*k <;> trivial,ih y]) simpa only [Nat.mul_succ,Nat.add_comm] using h variable (C : FiniteChain X) (Q : KilledKernel (FiniteChain.Outside A)) (hQ : ∀ x y,Q.Q x y=C.P x.val y.val) (hstep : ∀ x φ,(step x).expectation φ=C.apply φ x) lemma partialGreen_succ_apply (k : ℕ) (f : FiniteChain.Outside A → ℝ) (x : FiniteChain.Outside A) : Q.partialGreen (k+1) f x=f x+Q.apply (Q.partialGreen k f) x := by unfold KilledKernel.partialGreen rw [Finset.sum_range_succ'] simp only [KilledKernel.iterate_succ,KilledKernel.iterate_zero] rw [KilledKernel.apply_sum] ring include hQ hstep in lemma hittingTree_outside (k : ℕ) (φ : FiniteChain.Inside A → ℝ) (x : FiniteChain.Outside A) : (hittingTree step A k x.val).expectation (DrawTree.optionValue φ)= Q.partialGreen k (fun z => ∑ y : FiniteChain.Inside A,C.P z.val y.val*φ y) x := by induction k generalizing x with | zero => simp [hittingTree,DrawTree.expectation,DrawTree.optionValue,KilledKernel.partialGreen] | succ k ih => rw [hittingTree,DrawTree.expectation_bind,hstep,FiniteChain.apply] rw [←Fintype.sum_subtype_add_sum_subtype A] have hin : (∑ y : FiniteChain.Inside A,C.P x.val y.val* (if hy : A y.val then DrawTree.leaf (some (⟨y.val,hy⟩ : FiniteChain.Inside A)) else hittingTree step A k y.val).expectation (DrawTree.optionValue φ))= ∑ y : FiniteChain.Inside A,C.P x.val y.val*φ y := by apply Finset.sum_congr rfl; intro y _ simp only [dite_eq_left y.property,DrawTree.expectation,DrawTree.optionValue] have hout : (∑ y : FiniteChain.Outside A,C.P x.val y.val* (if hy : A y.val then DrawTree.leaf (some (⟨y.val,hy⟩ : FiniteChain.Inside A)) else hittingTree step A k y.val).expectation (DrawTree.optionValue φ))= Q.apply (Q.partialGreen k (fun z => ∑ y : FiniteChain.Inside A,C.P z.val y.val*φ y)) x := by unfold KilledKernel.apply apply Finset.sum_congr rfl; intro y _ rw [dite_eq_right y.property,ih,hQ] rw [hin,hout,partialGreen_succ_apply] include hQ hstep in lemma hittingTree_inside (k : ℕ) (x : FiniteChain.Inside A) (φ : FiniteChain.Inside A → ℝ) : (hittingTree step A (k+1) x.val).expectation (DrawTree.optionValue φ)= ∑ y : FiniteChain.Inside A,C.cappedTrace A Q k x y*φ y := by rw [hittingTree,DrawTree.expectation_bind,hstep,FiniteChain.apply] rw [←Fintype.sum_subtype_add_sum_subtype A] have hin : (∑ y : FiniteChain.Inside A,C.P x.val y.val* (if hy : A y.val then DrawTree.leaf (some (⟨y.val,hy⟩ : FiniteChain.Inside A)) else hittingTree step A k y.val).expectation (DrawTree.optionValue φ))= ∑ y : FiniteChain.Inside A,C.P x.val y.val*φ y := by apply Finset.sum_congr rfl; intro y _ simp only [dite_eq_left y.property,DrawTree.expectation,DrawTree.optionValue] have hout : (∑ y : FiniteChain.Outside A,C.P x.val y.val* (if hy : A y.val then DrawTree.leaf (some (⟨y.val,hy⟩ : FiniteChain.Inside A)) else hittingTree step A k y.val).expectation (DrawTree.optionValue φ))= ∑ z : FiniteChain.Outside A,C.P x.val z.val* Q.partialGreen k (fun t => ∑ y : FiniteChain.Inside A,C.P t.val y.val*φ y) z := by apply Finset.sum_congr rfl; intro y _ rw [dite_eq_right y.property,hittingTree_outside step A C Q hQ hstep] rw [hin,hout] simp only [FiniteChain.cappedTrace,add_mul,Finset.sum_add_distrib] congr 1 simp only [Finset.sum_mul] rw [Finset.sum_comm] apply Finset.sum_congr rfl; intro z _ simp only [mul_assoc] rw [←Finset.mul_sum,KilledKernel.partialGreen_sum] congr 1 apply Finset.sum_congr rfl; intro y _ unfold KilledKernel.partialGreen simp_rw [show (fun t : FiniteChain.Outside A => C.P t.val y.val*φ y)=fun t => φ y*C.P t.val y.val by funext t; ring] simp only [KilledKernel.iterate_mul,←Finset.mul_sum] ring end DrawHitting namespace DrawTree open scoped BigOperators Classical variable {X Y : Type*} [sectionInstance117 : Fintype X] omit sectionInstance117 in lemma map_fits [Fintype X] (t : DrawTree X) (f : X → Y) (H M : ℕ) (ht : Fits H M t) : Fits H M (t.map f) := by have h := fits_bind H M 0 t (fun x => .leaf (f x)) ht (fun _ => trivial) simpa only [map,Nat.add_zero] using h def sample (step : X → DrawTree X) : (k : ℕ) → X → DrawTree (FiniteChain.Sample X k) | 0,x => .leaf x | k+1,x => (step x).bind (fun y => (sample step k y).map (fun v => (x,v))) lemma sampleMass_delta (C : FiniteChain X) (ν : X → ℝ) (k : ℕ) (v : FiniteChain.Sample X k) : (∑ x,ν x*C.sampleMass (fun y => if x=y then 1 else 0) v)=C.sampleMass ν v := by cases k with | zero => dsimp only [FiniteChain.Sample] at v change (∑ x : X,ν x*(if x=v then 1 else 0))=ν v simp | succ k => change (∑ x,ν x*((if x=v.1 then 1 else 0)*C.sampleMass (C.P v.1) v.2))=_ change (∑ x : X,ν x*((if x=v.1 then 1 else 0)*C.sampleMass (C.P v.1) v.2))=ν v.1*C.sampleMass (C.P v.1) v.2 simp lemma sample_expectation (step : X → DrawTree X) (C : FiniteChain X) (hs : ∀ x φ,(step x).expectation φ=C.apply φ x) (k : ℕ) (x : X) (F : FiniteChain.Sample X k → ℝ) : (sample step k x).expectation F=∑ v : FiniteChain.Sample X k,C.sampleMass (fun y => if x=y then 1 else 0) v*F v := by induction k generalizing x with | zero => dsimp only [FiniteChain.Sample,FiniteChain.sampleFintype] at F ⊢ change F x=∑ v : X,(if x=v then (1:ℝ) else 0)*F v simp | succ k ih => dsimp only [FiniteChain.Sample,FiniteChain.sampleFintype] at F ⊢ change ((step x).bind (fun y => (sample step k y).map (fun v : FiniteChain.Sample X k => (x,v)))).expectation F=∑ v : X × FiniteChain.Sample X k,_ rw [expectation_bind] simp_rw [expectation_map,ih] rw [hs,FiniteChain.apply,Fintype.sum_prod_type] simp only [FiniteChain.sampleMass,ite_mul,one_mul,zero_mul] simp only [Finset.sum_ite_irrel,Finset.sum_const_zero,Finset.sum_ite_eq,Finset.mem_univ,ite_true] simp only [Finset.mul_sum] rw [Finset.sum_comm] apply Finset.sum_congr rfl; intro v _ simp only [←mul_assoc] rw [←Finset.sum_mul,sampleMass_delta] lemma sample_start_expectation (start : DrawTree (Option X)) (step : X → DrawTree X) (ν : X → ℝ) (C : FiniteChain X) (hstart : ∀ φ,start.expectation (optionValue φ)=∑ x,ν x*φ x) (hs : ∀ x φ,(step x).expectation φ=C.apply φ x) (k : ℕ) (F : FiniteChain.Sample X k → ℝ) : (start.optionBind (fun x => (sample step k x).map some)).expectation (optionValue F)= ∑ v : FiniteChain.Sample X k,C.sampleMass ν v*F v := by rw [expectation_optionBind,hstart] simp_rw [expectation_map] simp only [optionValue] simp_rw [sample_expectation step C hs,Finset.mul_sum] rw [Finset.sum_comm] apply Finset.sum_congr rfl; intro v _ simp only [←mul_assoc] rw [←Finset.sum_mul] congr 1 exact sampleMass_delta C ν k v lemma sample_fits (step : X → DrawTree X) (H M k : ℕ) (hs : ∀ x,Fits H M (step x)) (x : X) : Fits H (M*k) (sample step k x) := by induction k generalizing x with | zero => trivial | succ k ih => unfold sample have h := fits_bind H M (M*k) (step x) (fun y => (sample step k y).map (fun v : FiniteChain.Sample X k => (x,v))) (hs x) (by intro y; exact map_fits _ _ H (M*k) (ih y)) simpa only [FiniteChain.Sample,sample,Nat.mul_succ,Nat.add_comm] using h def history (K : List X → DrawTree (Option X)) : ℕ → List X → DrawTree (Option (List X)) | 0,h => pureSome h | k+1,h => (K h).optionBind (fun x => history K k (h++[x])) lemma history_expectation (K : List X → DrawTree (Option X)) (P : List X → X → ℝ) (hK : Matches K P) (k : ℕ) (h : List X) (F : List X → ℝ) : (history K k h).expectation (optionValue F)=FiniteExperiment.expect P k h F := by induction k generalizing h with | zero => rfl | succ k ih => rw [history,expectation_optionBind,hK] simp_rw [ih] rfl omit sectionInstance117 in lemma history_fits [Fintype X] (K : List X → DrawTree (Option X)) (H M k : ℕ) (hK : ∀ h,Fits H M (K h)) (h : List X) : Fits H (M*k) (history K k h) := by induction k generalizing h with | zero => trivial | succ k ih => unfold history have hh := optionBind_fits (K h) (fun x => history K k (h++[x])) H M (M*k) (hK h) (fun x => ih (h++[x])) simpa only [FiniteChain.Sample,sample,Nat.mul_succ,Nat.add_comm] using hh end DrawTree section DrawActual open scoped BigOperators Classical variable (n : ℕ) (hn : 0 pairedSlots n noncomputable def rationalStored (h : List (PhaseSample n N)) (j : ℕ) := rationalHistory GS (observedSets n N) (h.take j) lemma rationalStored_cast (h : List (PhaseSample n N)) (j : ℕ) (p r) : (rationalStored n N h j p r:ℝ)=storedWeights n N h j p r := by exact rationalHistory_cast GS (observedSets n N) (h.take j) p r lemma rationalStored_pos (h : List (PhaseSample n N)) (hp : HistoryPositive n N h) (j : ℕ) (p r) : 0 hittingTree (actualStepTree n hn M N h j) (plainPredicate GS) (cap+1) x.val lemma actualTraceTree_matches (h : List (PhaseSample n N)) (hp : HistoryPositive n N h) (j cap : ℕ) : DrawTree.Matches (actualTraceTree n hn M N h j cap) (actualCappedTrace n hn M j (storedWeights n N h j) (historyPositive_all n N h hp j) cap).P := by intro x φ exact hittingTree_inside (actualStepTree n hn M N h j) (plainPredicate GS) (metropolisChain GS (pairedSlots_fresh n) (pairedSlots_ne_nil n hn) (pairedSlots_cover n) (storedWeights n N h j) (annealWeight M n j) (historyPositive_all n N h hp j) (annealWeight_pos M n j hn)) (metropolisKilled GS (pairedSlots_fresh n) (pairedSlots_ne_nil n hn) (pairedSlots_cover n) (storedWeights n N h j) (annealWeight M n j) (historyPositive_all n N h hp j) (annealWeight_pos M n j hn)) (by intros; rfl) (actualStepTree_expectation n hn M N h hp j) cap x φ noncomputable def actualRestartTree (h : List (PhaseSample n N)) (cap : ℕ) : ℕ → DrawTree (Option (PlainIndex GS)) | 0 => letI := plainIndex_nonempty GS (pairedSlots_fresh n) (pairedSlots_cover n) (DrawTree.uniformChoice (PlainIndex GS)).map some | j+1 => (actualRestartTree h cap j).optionBind (DrawTree.iterate (actualTraceTree n hn M N h (j+1) cap) (20*n^4*(n*(L+1)+2))) lemma actualRestartTree_expectation (h : List (PhaseSample n N)) (hp : HistoryPositive n N h) (cap j : ℕ) (φ : PlainIndex GS → ℝ) : (actualRestartTree n hn M N L h cap j).expectation (DrawTree.optionValue φ)= ∑ x,restartLaw n hn M L cap (storedWeights n N h) (historyPositive_all n N h hp) j x*φ x := by induction j generalizing φ with | zero => rw [actualRestartTree,DrawTree.expectation_map,DrawTree.uniformChoice_expectation] simp only [DrawTree.optionValue,uniformAverage,restartLaw,uniformPlain,plainIndex_card,Nat.cast_pow,Nat.cast_ofNat] rw [Finset.sum_div] apply Finset.sum_congr rfl; intro x _; ring | succ j ih => rw [actualRestartTree,DrawTree.expectation_optionBind,ih] have hi := DrawTree.iterate_matches _ _ (actualTraceTree_matches n hn M N h hp (j+1) cap) (20*n^4*(n*(L+1)+2)) unfold DrawTree.Matches at hi simp_rw [hi] simp only [Finset.mul_sum] simp only [restartLaw,FiniteKernel.push,Finset.sum_mul,mul_assoc] rw [Finset.sum_comm] noncomputable def actualStartTree (h : List (PhaseSample n N)) : DrawTree (Option (ChainIndex GS)) := (actualRestartTree n hn M N L h (restartCap n L) h.length).map (Option.map Subtype.val) lemma actualStartTree_expectation (h : List (PhaseSample n N)) (hp : HistoryPositive n N h) (φ : ChainIndex GS → ℝ) : (actualStartTree n hn M N L h).expectation (DrawTree.optionValue φ)=∑ x,phaseStart n hn M N L h hp x*φ x := by rw [actualStartTree,DrawTree.expectation_map] have hf : (fun a : Option (PlainIndex GS) => DrawTree.optionValue φ (Option.map Subtype.val a))= DrawTree.optionValue (fun a => φ a.val) := by funext a; cases a <;> rfl rw [hf,actualRestartTree_expectation n hn M N L h hp] rw [←Fintype.sum_subtype_add_sum_subtype (plainPredicate GS)] simp only [phaseStart,plainLift] have hin : (∑ x : PlainIndex GS,(if hx : PlainState GS x.val.val then restartLaw n hn M L (restartCap n L) (storedWeights n N h) (historyPositive_all n N h hp) h.length ⟨x.val,hx⟩ else 0)*φ x.val)= ∑ x : PlainIndex GS,restartLaw n hn M L (restartCap n L) (storedWeights n N h) (historyPositive_all n N h hp) h.length x*φ x.val := by apply Finset.sum_congr rfl; intro x _; rw [dite_eq_left x.property] rw [hin] have hout : (∑ x : FiniteChain.Outside (plainPredicate GS), (if hx : PlainState GS x.val.val then restartLaw n hn M L (restartCap n L) (storedWeights n N h) (historyPositive_all n N h hp) h.length ⟨x.val,hx⟩ else 0)*φ x.val)=0 := by apply Finset.sum_eq_zero; intro x _; rw [dite_eq_right x.property,zero_mul] rw [hout,add_zero] noncomputable def actualPhaseTree (h : List (PhaseSample n N)) : DrawTree (Option (PhaseSample n N)) := if HistoryPositive n N h then (actualStartTree n hn M N L h).optionBind (fun x => (DrawTree.sample (actualStepTree n hn M N h h.length) (N-1) x).map some) else .leaf none lemma actualPhaseTree_matches : DrawTree.Matches (actualPhaseTree n hn M N L) (phaseKernel n hn M N L) := by intro h φ unfold actualPhaseTree phaseKernel split_ifs with hp · exact DrawTree.sample_start_expectation _ _ _ _ (actualStartTree_expectation n hn M N L h hp) (actualStepTree_expectation n hn M N h hp h.length) (N-1) φ · simp [DrawTree.expectation,DrawTree.optionValue] end DrawActual open scoped BigOperators Classical variable (n : ℕ) (hn : 0 pairedMatroid M₁ M₂ local notation "GS" => pairedSlots n noncomputable def rationalEstimate (h : List (PhaseSample n N)) : ℚ := (2:ℚ)^n * ∏ j ∈ Finset.range L, rationalRatio GS (fun S => rationalRho n^(n-((K).eRk S).toNat)) (historySample (observedSets n N) h j) lemma rationalEstimate_cast (h : List (PhaseSample n N)) : (rationalEstimate n M₁ M₂ N L h:ℝ)=historyEstimate n N L K h := by simp only [rationalEstimate,Rat.cast_mul,Rat.cast_pow,Rat.cast_ofNat,Rat.cast_prod,rationalRatio_cast, rationalRho_cast,historyEstimate] noncomputable def rationalGuard (h : List (PhaseSample n N)) (x : PlainIndex GS) : ℚ := if Witnessed n M₁ M₂ x then rationalEstimate n M₁ M₂ N L h else 0 lemma rationalGuard_cast (h : List (PhaseSample n N)) (x : PlainIndex GS) : (rationalGuard n M₁ M₂ N L h x:ℝ)=guardedEstimate n M₁ M₂ N L h x := by unfold rationalGuard guardedEstimate split_ifs <;> simp [rationalEstimate_cast] include hn in lemma rationalGuard_nonneg (h : List (PhaseSample n N)) (x : PlainIndex GS) : 0≤rationalGuard n M₁ M₂ N L h x := by have hh := guardedEstimate_nonneg n hn M₁ M₂ N L h x rw [←rationalGuard_cast] at hh exact_mod_cast hh lemma rationalGuard_zero (hE₂ : M₂.E=Set.univ) (hr : M₁.eRank=M₂.eRank) (hZ : commonBaseCount M₁ M₂=0) (h : List (PhaseSample n N)) (x : PlainIndex GS) : rationalGuard n M₁ M₂ N L h x=0 := by have hh := guardedEstimate_zero n M₁ M₂ N L hE₂ hr hZ h x rw [←rationalGuard_cast] at hh exact_mod_cast hh noncomputable def rationalWitnessTree (h : List (PhaseSample n N)) : DrawTree (Option (PlainIndex GS)) := if HistoryPositive n N h then actualRestartTree n hn K N L h (restartCap n L) h.length else .leaf none lemma rationalWitnessTree_expectation (h : List (PhaseSample n N)) (φ : PlainIndex GS → ℝ) : (rationalWitnessTree n hn M₁ M₂ N L h).expectation (DrawTree.optionValue φ)= ∑ x,witnessKernel n hn M₁ M₂ N L h x*φ x := by unfold rationalWitnessTree witnessKernel split_ifs with hp · exact actualRestartTree_expectation n hn K N L h hp (restartCap n L) h.length φ · simp [DrawTree.expectation,DrawTree.optionValue] noncomputable def rationalAlgorithmTree : DrawTree (Option ℚ) := (DrawTree.history (actualPhaseTree n hn K N L) L []).optionBind (fun h => (rationalWitnessTree n hn M₁ M₂ N L h).map (Option.map (rationalGuard n M₁ M₂ N L h))) lemma rationalAlgorithmTree_expectation (F : ℚ → ℝ) : (rationalAlgorithmTree n hn M₁ M₂ N L).expectation (DrawTree.optionValue F)= FiniteExperiment.expect (phaseKernel n hn K N L) L [] (fun h => ∑ x,witnessKernel n hn M₁ M₂ N L h x*F (rationalGuard n M₁ M₂ N L h x)) := by rw [rationalAlgorithmTree,DrawTree.expectation_optionBind,DrawTree.history_expectation _ _ (actualPhaseTree_matches n hn K N L)] congr 1; funext h rw [DrawTree.expectation_map] have hf : (fun a : Option (PlainIndex GS) => DrawTree.optionValue F (Option.map (rationalGuard n M₁ M₂ N L h) a))= DrawTree.optionValue (fun x => F (rationalGuard n M₁ M₂ N L h x)) := by funext a; cases a <;> rfl rw [hf,rationalWitnessTree_expectation] lemma rationalAlgorithmTree_success_eq (ε : ℚ) : (rationalAlgorithmTree n hn M₁ M₂ N L).expectation (DrawTree.optionValue (fun z => if relativeAccuracy ε (commonBaseCount M₁ M₂) z then 1 else 0))= actualRealSuccess n hn M₁ M₂ N L (ε:ℝ) := by rw [rationalAlgorithmTree_expectation] unfold actualRealSuccess congr 1; funext h apply Finset.sum_congr rfl; intro x _ have he : relativeAccuracy ε (commonBaseCount M₁ M₂) (rationalGuard n M₁ M₂ N L h x) ↔ (1-(ε:ℝ))*(commonBaseCount M₁ M₂:ℝ)≤guardedEstimate n M₁ M₂ N L h x ∧ guardedEstimate n M₁ M₂ N L h x≤(1+(ε:ℝ))*(commonBaseCount M₁ M₂:ℝ) := by rw [←rationalGuard_cast] unfold relativeAccuracy constructor <;> intro hh <;> exact_mod_cast hh simp only [he,mul_ite,mul_one,mul_zero] include hn in theorem rational_algorithm_success (hE₁ : M₁.E=Set.univ) (hE₂ : M₂.E=Set.univ) (hr : M₁.eRank=M₂.eRank) (ε : ℚ) (hε0 : 0<ε) (hε1 : ε<1) (b : ℕ) (hb : (1/2:ℝ)^b ≤ (ε:ℝ)/10) (hZ : 0 if relativeAccuracy ε (commonBaseCount M₁ M₂) z then 1 else 0)) := by rw [rationalAlgorithmTree_success_eq] exact real_annealing_success n hn M₁ M₂ N hE₁ hE₂ hr (ε:ℝ) (by exact_mod_cast hε0) (by exact_mod_cast hε1) b hb hZ hN end open scoped BigOperators Classical def RatBound (q : ℚ) (B : ℕ) : Prop := ∃ a b : ℕ,a≤B ∧ b≤B ∧ 0 simpa using one 1 (by decide) | succ k ih => simpa only [pow_succ] using ih.mul hq lemma min_one (hq : RatBound q B) : RatBound (min 1 q) B := by by_cases h : 1≤q · rw [min_eq_left h]; exact one B hq.one_le · rw [min_eq_right (le_of_not_ge h)]; exact hq lemma den_le (hq : RatBound q B) : q.den≤B := by obtain ⟨a,b,ha,hb,hpos,rfl⟩ := hq have he : ((a:ℚ)/(b:ℚ))=Rat.divInt (a:ℤ) (b:ℤ) := by simp [Rat.divInt_eq_div] rw [he] have hd := Rat.den_dvd (a:ℤ) (b:ℤ) exact (Nat.le_of_dvd hpos (Int.natCast_dvd_natCast.mp hd)).trans hb lemma num_le (hq : RatBound q B) : q.num.natAbs≤B := by obtain ⟨a,b,ha,hb,hpos,rfl⟩ := hq have he : ((a:ℚ)/(b:ℚ))=Rat.divInt (a:ℤ) (b:ℤ) := by simp [Rat.divInt_eq_div] rw [he,Rat.num_divInt] have hs : (b:ℤ).sign=1 := Int.sign_eq_one_of_pos (by exact_mod_cast hpos) rw [hs,one_mul] rw [Int.natAbs_ediv,Int.natAbs_natCast,Int.natAbs_natCast] exact (Nat.div_le_self _ _).trans ha end RatBound section ActualSize open scoped BigOperators Classical lemma RatBound.nat_div (a b B : ℕ) (ha : a≤B) (hb : b≤B) (hB : 0 if P x then (1:ℚ) else 0)).sum=(l.countP (fun x => decide (P x)):ℚ) := by induction l with | nil => simp | cons x l ih => by_cases hx : P x <;> simp [hx,ih,add_comm] variable {Γ : Type*} [sectionInstance118 : Fintype Γ] [sectionInstance119 : DecidableEq Γ] omit sectionInstance118 sectionInstance119 in lemma rationalTypeRatio [Fintype Γ] [DecidableEq Γ] (gs : List (Γ × Γ)) (l : List (Set Γ)) (p r : Γ × Γ) : rationalEmpirical (rationalPlain gs (fun _ => 1)) l / rationalEmpirical (rationalDefect gs p r) l = (l.countP (fun S => decide (PlainState gs S)):ℚ)/ (l.countP (fun S => decide (DefectState gs p r S)):ℚ) := by unfold rationalEmpirical rationalPlain rationalDefect rw [indicator_list_sum,indicator_list_sum] by_cases hz : l.length=0 · have he : l=[] := List.length_eq_zero_iff.mp hz simp [he] · exact div_div_div_cancel_right₀ (by exact_mod_cast hz : (l.length:ℚ)≠0) _ _ lemma rationalLearn_bound (gs : List (Γ × Γ)) (w : (Γ × Γ) → (Γ × Γ) → ℚ) (l : List (Set Γ)) (B N : ℕ) (hN : 0 simpa [rationalHistory] using RatBound.nat 4 4 (by omega) (by omega) | append_singleton h x ih => have he : rationalHistory gs sample (h++[x])=rationalLearn gs (rationalHistory gs sample h) (sample x) := by funext p r; simp [rationalHistory,List.foldl_append] rw [he] have hh := rationalLearn_bound gs (rationalHistory gs sample h) (sample x) (4*N^h.length) N hN (hs x) ih p r simpa only [List.length_append,List.length_singleton,pow_succ,Nat.mul_assoc] using hh omit sectionInstance119 in lemma rationalMultiplier_bound [DecidableEq Γ] (gs : List (Γ × Γ)) (w : (Γ × Γ) → (Γ × Γ) → ℚ) (B : ℕ) (hB : 0 (observedSets_length n N hN x).le) (h.take j) p r apply hd.mono apply Nat.mul_le_mul_left apply Nat.pow_le_pow_right hN rw [List.length_take] exact (Nat.min_le_right _ _).trans hlen lemma rationalWeight_bound (hn : 0 pairedSlots n local notation "H" => drawWordBound n N L include hN in lemma actualStepTree_fits (h : List (PhaseSample n N)) (hlen : h.length≤L) (j : ℕ) (hj : j≤L) (x : ChainIndex GS) : DrawTree.Fits H 3 (actualStepTree n hn M N h j x) := by let : Nonempty (ExchangeChoice x.val) := Fintype.card_pos_iff.mp (by rw [exchangeChoice_card GS (pairedSlots_fresh n) (pairedSlots_cover n),pairedSlots_length]; positivity) unfold actualStepTree rationalMetropolis apply DrawTree.fits_bind H 1 2 _ _ · apply DrawTree.bernoulli_fits norm_num exact drawWordBound_ge_one n N L · intro lazy cases lazy with | true => trivial | false => simp only [Bool.false_eq_true,ite_false] apply DrawTree.fits_bind H 1 1 _ _ · apply DrawTree.uniformChoice_fits rw [exchangeChoice_card GS (pairedSlots_fresh n) (pairedSlots_cover n),pairedSlots_length] exact drawWordBound_exchange n N L · intro a unfold rationalExchange split_ifs · apply DrawTree.map_fits apply DrawTree.bernoulli_fits apply Nat.clog_le_of_le_pow exact (rationalAcceptance_bound n N L hN hn M h hlen j hj x _).den_le.trans (acceptance_word_bound n N L) · trivial include hN in lemma actualTraceTree_fits (h : List (PhaseSample n N)) (hlen : h.length≤L) (j cap : ℕ) (hj : j≤L) (x : PlainIndex GS) : DrawTree.Fits H (3*(cap+1)) (actualTraceTree n hn M N h j cap x) := by exact hittingTree_fits _ _ H 3 (cap+1) (actualStepTree_fits n hn M N L hN h hlen j hj) x.val include hN in lemma actualRestartTree_fits (h : List (PhaseSample n N)) (hlen : h.length≤L) (cap j : ℕ) (hj : j≤L) : DrawTree.Fits H (1+3*j*(cap+1)*(20*n^4*(n*(L+1)+2))) (actualRestartTree n hn M N L h cap j) := by let := plainIndex_nonempty GS (pairedSlots_fresh n) (pairedSlots_cover n) induction j with | zero => rw [actualRestartTree] simp only [Nat.mul_zero,Nat.zero_mul,Nat.add_zero] apply DrawTree.map_fits apply DrawTree.uniformChoice_fits rw [plainIndex_card,Nat.clog_pow 2 n (by omega)] exact drawWordBound_ge_n n N L | succ j ih => rw [actualRestartTree] have hh := DrawTree.optionBind_fits (actualRestartTree n hn M N L h cap j) (DrawTree.iterate (actualTraceTree n hn M N h (j+1) cap) (20*n^4*(n*(L+1)+2))) H (1+3*j*(cap+1)*(20*n^4*(n*(L+1)+2))) (3*(cap+1)*(20*n^4*(n*(L+1)+2))) (ih (by omega)) (DrawTree.iterate_fits _ H (3*(cap+1)) _ (actualTraceTree_fits n hn M N L hN h hlen (j+1) cap hj)) convert hh using 1 ; ring def phaseDrawBound (n N L : ℕ) : ℕ := 1+3*L*(restartCap n L+1)*(20*n^4*(n*(L+1)+2))+3*N include hN in lemma actualPhaseTree_fits (h : List (PhaseSample n N)) (hlen : h.length≤L) : DrawTree.Fits H (phaseDrawBound n N L) (actualPhaseTree n hn M N L h) := by unfold actualPhaseTree split_ifs · have hstart : DrawTree.Fits H (1+3*L*(restartCap n L+1)*(20*n^4*(n*(L+1)+2))) (actualStartTree n hn M N L h) := by apply DrawTree.map_fits apply DrawTree.fits_mono_steps H _ _ _ _ (actualRestartTree_fits n hn M N L hN h hlen (restartCap n L) h.length hlen) gcongr apply DrawTree.optionBind_fits _ _ H _ (3*N) hstart intro x apply DrawTree.map_fits apply DrawTree.fits_mono_steps H (3*(N-1)) (3*N) (by omega) exact DrawTree.sample_fits _ H 3 (N-1) (actualStepTree_fits n hn M N L hN h hlen h.length hlen) x · cases phaseDrawBound n N L <;> trivial end ActualFits namespace DrawTree variable {A B C : Type*} lemma bind_assoc (t : DrawTree A) (f : A → DrawTree B) (g : B → DrawTree C) : (t.bind f).bind g=t.bind (fun a => (f a).bind g) := by induction t with | leaf a => rfl | draw v k ih => simp only [bind,ih] lemma optionBind_assoc (t : DrawTree (Option A)) (f : A → DrawTree (Option B)) (g : B → DrawTree (Option C)) : (t.optionBind f).optionBind g=t.optionBind (fun a => (f a).optionBind g) := by simp only [optionBind,bind_assoc] congr 1; funext a; cases a <;> rfl lemma leaf_fits (H M : ℕ) (a : A) : Fits H M (.leaf a) := by cases M <;> trivial end DrawTree section AlgorithmFits open scoped BigOperators Classical variable (n : ℕ) (hn : 0 pairedMatroid M₁ M₂ local notation "H" => drawWordBound n N L local notation "B" => phaseDrawBound n N L include hN in lemma rationalWitnessTree_fits (h : List (PhaseSample n N)) (hlen : h.length≤L) : DrawTree.Fits H B (rationalWitnessTree n hn M₁ M₂ N L h) := by unfold rationalWitnessTree split_ifs · apply DrawTree.fits_mono_steps H _ B _ _ (actualRestartTree_fits n hn K N L hN h hlen (restartCap n L) h.length hlen) unfold phaseDrawBound have hh : 3*h.length*(restartCap n L+1)*(20*n^4*(n*(L+1)+2))≤ 3*L*(restartCap n L+1)*(20*n^4*(n*(L+1)+2)) := by gcongr omega · exact DrawTree.leaf_fits H B none include hN in lemma rational_history_finish_fits (h : List (PhaseSample n N)) (k : ℕ) (hlen : h.length+k≤L) : DrawTree.Fits H (B*(k+1)) ((DrawTree.history (actualPhaseTree n hn K N L) k h).optionBind (fun h => (rationalWitnessTree n hn M₁ M₂ N L h).map (Option.map (rationalGuard n M₁ M₂ N L h)))) := by induction k generalizing h with | zero => simp only [DrawTree.history,DrawTree.pureSome,DrawTree.optionBind,DrawTree.bind,Nat.zero_add,Nat.mul_one] exact DrawTree.map_fits _ _ H B (rationalWitnessTree_fits n hn M₁ M₂ N L hN h (by omega)) | succ k ih => rw [DrawTree.history,DrawTree.optionBind_assoc] have hh := DrawTree.optionBind_fits (actualPhaseTree n hn K N L h) (fun x => (DrawTree.history (actualPhaseTree n hn K N L) k (h++[x])).optionBind (fun h => (rationalWitnessTree n hn M₁ M₂ N L h).map (Option.map (rationalGuard n M₁ M₂ N L h)))) H B (B*(k+1)) (actualPhaseTree_fits n hn K N L hN h (by omega)) (by intro x; apply ih; simp only [List.length_append,List.length_singleton]; omega) convert hh using 1 ; ring def algorithmDrawBound (n N L : ℕ) : ℕ := phaseDrawBound n N L*(L+1) include hN in lemma rationalAlgorithmTree_fits : DrawTree.Fits H (algorithmDrawBound n N L) (rationalAlgorithmTree n hn M₁ M₂ N L) := rational_history_finish_fits n hn M₁ M₂ N L hN [] L (by simp) end AlgorithmFits namespace DrawTree variable {A B : Type*} def All (p : A → Prop) : DrawTree A → Prop | .leaf a => p a | .draw _ k => ∀ i,All p (k i) lemma all_bind (t : DrawTree A) (f : A → DrawTree B) (p : B → Prop) (hf : ∀ a,All p (f a)) : All p (t.bind f) := by induction t with | leaf a => exact hf a | draw v k ih => exact ih lemma all_map (t : DrawTree A) (f : A → B) (p : B → Prop) (hf : ∀ a,p (f a)) : All p (t.map f) := all_bind t _ p hf lemma run_all (H D M : ℕ) (t : DrawTree A) (p : A → Prop) (ht : All p t) (bits) (a : A) (ha : run H D M t bits=some a) : p a := by induction M generalizing t with | zero => cases t with | leaf x => simp only [run,Option.some.injEq] at ha; exact ha ▸ ht | draw v k => simp [run] at ha | succ M ih => cases t with | leaf x => simp only [run,Option.some.injEq] at ha; exact ha ▸ ht | draw v k => simp only [run] at ha split_ifs at ha with h · split at ha · simp at ha · exact ih _ (ht _) _ ha end DrawTree section AlgorithmAll open scoped Classical variable (n : ℕ) (hn : 0 ∀ z,a=some z → 0≤z ∧ (M₂.E=Set.univ → M₁.eRank=M₂.eRank → commonBaseCount M₁ M₂=0 → z=0)) (rationalAlgorithmTree n hn M₁ M₂ N L) := by unfold rationalAlgorithmTree DrawTree.optionBind apply DrawTree.all_bind intro a cases a with | none => intro z; simp | some h => apply DrawTree.all_map intro a cases a with | none => intro z; simp | some x => intro z hz simp only [Option.map_some,Option.some.injEq] at hz subst z exact ⟨rationalGuard_nonneg n hn M₁ M₂ N L h x, fun hE hr hZ => rationalGuard_zero n M₁ M₂ N L hE hr hZ h x⟩ end AlgorithmAll open scoped BigOperators Classical lemma uniformAverage_one_sub {X : Type*} [Fintype X] [Nonempty X] (f : X → ℝ) : uniformAverage (fun x => 1-f x)=1-uniformAverage f := by unfold uniformAverage simp only [Finset.sum_sub_distrib,Finset.sum_const,Finset.card_univ,nsmul_eq_mul,mul_one] rw [sub_div,div_self (by exact_mod_cast ne_of_gt (Fintype.card_pos))] lemma rejectionBudget (M : ℕ) : (M:ℝ)*(1/2:ℝ)^(M+6)≤1/64 := by have hM : (M:ℝ)≤(2:ℝ)^M := by exact_mod_cast (Nat.lt_two_pow_self (n:=M)).le have h := mul_le_mul_of_nonneg_right hM (by positivity : 0≤(1/2:ℝ)^(M+6)) apply h.trans rw [pow_add,←mul_assoc,←mul_pow] norm_num abbrev FairBank (n N L : ℕ) := Fin (algorithmDrawBound n N L) → Fin (algorithmDrawBound n N L+6) → BitWord (drawWordBound n N L) noncomputable def fairOutput (n : ℕ) (hn : 0 simp | some a => cases a with | none => simp | some z => simp only [Option.join_some,Option.getD_some] exact (DrawTree.run_all _ _ _ _ _ (rationalAlgorithmTree_all n hn M₁ M₂ N L) bits (some z) he z rfl).1 lemma fairOutput_zero (n : ℕ) (hn : 0 simp | some a => cases a with | none => simp | some z => simp only [Option.join_some,Option.getD_some] exact (DrawTree.run_all _ _ _ _ _ (rationalAlgorithmTree_all n hn M₁ M₂ N L) bits (some z) he z rfl).2 hE₂ hr hZ theorem fair_single_success (n : ℕ) (hn : 0 if relativeAccuracy ε (commonBaseCount M₁ M₂) (fairOutput n hn M₁ M₂ N (annealLength n b) bits) then (1:ℝ) else 0) := by by_cases hZ : commonBaseCount M₁ M₂=0 · simp only [fairOutput_zero n hn M₁ M₂ N _ hE₂ hr hZ,hZ,relativeAccuracy,Nat.cast_zero,mul_zero,le_refl,and_self,ite_true,uniformAverage_const] norm_num have hN0 : 0 if relativeAccuracy ε (commonBaseCount M₁ M₂) z then 1 else 0 have hs := rational_algorithm_success n hn M₁ M₂ N hE₁ hE₂ hr ε hε0 hε1 b hb (Nat.pos_of_ne_zero hZ) hN have hrun := DrawTree.run_lower (drawWordBound n N L) (algorithmDrawBound n N L+6) (algorithmDrawBound n N L) (rationalAlgorithmTree n hn M₁ M₂ N L) (rationalAlgorithmTree_fits n hn M₁ M₂ N L hN0) (DrawTree.optionValue φ) (by intro a; cases a with | none => norm_num [DrawTree.optionValue] | some z => dsimp [DrawTree.optionValue,φ]; split_ifs <;> norm_num) (by intro a; cases a with | none => norm_num [DrawTree.optionValue] | some z => dsimp [DrawTree.optionValue,φ]; split_ifs <;> norm_num) have hm : uniformAverage (fun bits : FairBank n N L => DrawTree.optionValue (DrawTree.optionValue φ) (DrawTree.run (drawWordBound n N L) (algorithmDrawBound n N L+6) (algorithmDrawBound n N L) (rationalAlgorithmTree n hn M₁ M₂ N L) bits)) ≤ uniformAverage (fun bits : FairBank n N L => φ (fairOutput n hn M₁ M₂ N L bits)) := by apply uniformAverage_mono intro bits unfold fairOutput generalize DrawTree.run _ _ _ _ bits=a cases a with | none => dsimp [DrawTree.optionValue,φ]; split_ifs <;> norm_num | some a => cases a <;> dsimp [DrawTree.optionValue,φ] <;> split_ifs <;> norm_num have hbudget := rejectionBudget (algorithmDrawBound n N L) change 11/16≤uniformAverage (fun bits : FairBank n N L => φ (fairOutput n hn M₁ M₂ N L bits)) change 3/4≤(rationalAlgorithmTree n hn M₁ M₂ N L).expectation (DrawTree.optionValue φ) at hs linarith open scoped BigOperators Classical def rationalMedian (l : List ℚ) : ℚ := (l.mergeSort (· ≤ ·)).getD (l.length/2) 0 def outsideInterval (a b x : ℚ) : Bool := decide (¬(a≤x ∧ x≤b)) lemma median_bad_count (l : List ℚ) (hl : 0 hbad ⟨ha,hh⟩) have htail : (s.drop (l.length/2)).countP (outsideInterval a b)=(s.drop (l.length/2)).length := by apply List.countP_eq_length.mpr intro x hx obtain ⟨i,hi,rfl⟩ := List.getElem_of_mem hx rw [List.getElem_drop] apply decide_eq_true intro hh have hm := hs.getElem_le_getElem_of_le (i := l.length/2) (j := l.length/2+i) (hi := hk) (hj := by simp only [List.length_drop] at hi; omega) (by omega) exact (not_le_of_gt (hb.trans_le hm)) hh.2 have hdecomp := List.countP_append (p := outsideInterval a b) (l₁ := s.take (l.length/2)) (l₂ := s.drop (l.length/2)) rw [List.take_append_drop,htail,hc,List.length_drop,hlen] at hdecomp omega · have hfront : (s.take (l.length/2+1)).countP (outsideInterval a b)=(s.take (l.length/2+1)).length := by apply List.countP_eq_length.mpr intro x hx obtain ⟨i,hi,rfl⟩ := List.getElem_of_mem hx rw [List.getElem_take] apply decide_eq_true intro hh have hi' : i≤l.length/2 := by simp only [List.length_take] at hi; omega have hm := hs.getElem_le_getElem_of_le (i := i) (j := l.length/2) (hi := by simp only [List.length_take] at hi; omega) (hj := hk) hi' exact ha (hh.1.trans hm) have hdecomp := List.countP_append (p := outsideInterval a b) (l₁ := s.take (l.length/2+1)) (l₂ := s.drop (l.length/2+1)) rw [List.take_append_drop,hfront,hc,List.length_take,hlen] at hdecomp omega lemma uniformAverage_mul_const {X : Type*} [Fintype X] (f : X → ℝ) (c : ℝ) : uniformAverage (fun x => f x*c)=uniformAverage f*c := by unfold uniformAverage rw [← Finset.sum_mul] ring lemma countP_ofFn_cons {X : Type*} (p : X → Bool) (x : X) {R : ℕ} (xs : Fin R → X) : (List.ofFn (Fin.cons x xs)).countP p=(if p x then 1 else 0)+(List.ofFn xs).countP p := by rw [List.ofFn_succ] simp only [Fin.cons_zero,Fin.cons_succ,List.countP_cons] change (List.ofFn xs).countP p+(if p x then 1 else 0)=(if p x then 1 else 0)+(List.ofFn xs).countP p omega lemma independent_bad_moment {X : Type*} [Fintype X] [Nonempty X] (bad : X → Bool) (R : ℕ) : uniformAverage (fun xs : Fin R → X => (4:ℝ)^((List.ofFn xs).countP bad))= (1+3*uniformAverage (fun x => if bad x then (1:ℝ) else 0))^R := by induction R with | zero => simp [List.ofFn_zero,uniformAverage_const] | succ R ih => rw [uniformAverage_fin_succ] simp_rw [countP_ofFn_cons,pow_add,uniformAverage_mul_left,ih] rw [uniformAverage_mul_const] have he : (fun x : X => (4:ℝ)^(if bad x then 1 else 0:ℕ))= fun x => 1+3*(if bad x then (1:ℝ) else 0) := by funext x; cases bad x <;> norm_num rw [he,uniformAverage_add,uniformAverage_const,uniformAverage_mul_left,pow_succ] ring lemma countP_map {X Y : Type*} (l : List X) (f : X → Y) (p : Y → Bool) : (l.map f).countP p=l.countP (fun x => p (f x)) := by induction l with | nil => rfl | cons x xs ih => simp only [List.map_cons,List.countP_cons,ih] theorem median_failure_bound {X : Type*} [Fintype X] [Nonempty X] (output : X → ℚ) (a b : ℚ) (R : ℕ) (hR : 0 if outsideInterval a b (output x) then (1:ℝ) else 0)≤5/16) : uniformAverage (fun xs : Fin R → X => if outsideInterval a b (rationalMedian (List.ofFn (fun i => output (xs i)))) then (1:ℝ) else 0) ≤ (31/32:ℝ)^R := by let bad : X → Bool := fun x => outsideInterval a b (output x) have hx : ∀ xs : Fin R → X, (if outsideInterval a b (rationalMedian (List.ofFn (fun i => output (xs i)))) then (1:ℝ) else 0) ≤ (4:ℝ)^((List.ofFn xs).countP bad)/(2:ℝ)^R := by intro xs by_cases he : outsideInterval a b (rationalMedian (List.ofFn (fun i => output (xs i))))=true · rw [ite_eq_left he] have hc := median_bad_count (List.ofFn (fun i => output (xs i))) (by simpa using hR) a b (by simpa only [outsideInterval,decide_eq_true_eq] using he) have hmap : List.ofFn (fun i => output (xs i))=(List.ofFn xs).map output := by rw [List.map_ofFn]; rfl rw [hmap,countP_map,List.length_map,List.length_ofFn] at hc have hp : (2:ℝ)^R≤4^((List.ofFn xs).countP bad) := by calc (2:ℝ)^R ≤ 2^(2*((List.ofFn xs).countP bad)) := pow_le_pow_right₀ (by norm_num) hc _ = _ := by rw [pow_mul]; norm_num exact (le_div_iff₀ (by positivity)).mpr (by simpa using hp) · rw [ite_eq_right he]; positivity have hm := uniformAverage_mono _ _ hx have hrw : uniformAverage (fun xs : Fin R → X => (4:ℝ)^((List.ofFn xs).countP bad)/(2:ℝ)^R)= (1+3*uniformAverage (fun x => if bad x then (1:ℝ) else 0))^R/(2:ℝ)^R := by simp_rw [div_eq_mul_inv] rw [uniformAverage_mul_const,independent_bad_moment] rw [hrw] at hm apply hm.trans rw [←div_pow] apply pow_le_pow_left₀ (by apply div_nonneg _ (by norm_num) have hz := uniformAverage_nonneg (fun x => if bad x then (1:ℝ) else 0) (by intro x; split_ifs <;> norm_num) linarith) dsimp [bad] at * linarith def repetitionCount (δ : ℚ) : ℕ := 64*(δ.den.bits.length+1) lemma repetitionCount_pos (δ : ℚ) : 0 if outsideInterval a b (output x) then (1:ℝ) else 0)≤5/16) : 1-(δ:ℝ) ≤ uniformAverage (fun xs : Fin (repetitionCount δ) → X => if a≤rationalMedian (List.ofFn (fun i => output (xs i))) ∧ rationalMedian (List.ofFn (fun i => output (xs i)))≤b then (1:ℝ) else 0) := by have h := (median_failure_bound output a b (repetitionCount δ) (repetitionCount_pos δ) hbad).trans (confidence_decay δ hδ) have he : (fun xs : Fin (repetitionCount δ) → X => if outsideInterval a b (rationalMedian (List.ofFn (fun i => output (xs i)))) then (1:ℝ) else 0)= fun xs => 1-(if a≤rationalMedian (List.ofFn (fun i => output (xs i))) ∧ rationalMedian (List.ofFn (fun i => output (xs i)))≤b then (1:ℝ) else 0) := by funext xs simp only [outsideInterval,decide_eq_true_eq] split_ifs <;> simp_all rw [he] at h have hei : uniformAverage (fun xs : Fin (repetitionCount δ) → X => 1-(if a≤rationalMedian (List.ofFn (fun i => output (xs i))) ∧ rationalMedian (List.ofFn (fun i => output (xs i)))≤b then (1:ℝ) else 0))= 1-uniformAverage (fun xs : Fin (repetitionCount δ) → X => if a≤rationalMedian (List.ofFn (fun i => output (xs i))) ∧ rationalMedian (List.ofFn (fun i => output (xs i)))≤b then (1:ℝ) else 0) := by unfold uniformAverage simp only [Finset.sum_sub_distrib,Finset.sum_const,Finset.card_univ,nsmul_eq_mul,mul_one] rw [sub_div,div_self (by exact_mod_cast ne_of_gt (Fintype.card_pos))] rw [hei] at h linarith open scoped BigOperators Classical lemma rationalMedian_all (p : ℚ → Prop) (l : List ℚ) (h0 : p 0) (hl : ∀ z∈l,p z) : p (rationalMedian l) := by unfold rationalMedian by_cases h : l.length/2<(l.mergeSort (· ≤ ·)).length · rw [List.getD_eq_getElem _ _ h] apply hl exact (List.mem_mergeSort).mp (List.getElem_mem h) · have hl0 : l.length=0 := by simp only [List.length_mergeSort] at h; omega have he : l=[] := List.length_eq_zero_iff.mp hl0 simpa [he] using h0 def accuracyExponent (ε : ℚ) : ℕ := ε.den.bits.length+5 lemma accuracyExponent_spec (ε : ℚ) (hε : 0<ε) : (1/2:ℝ)^(accuracyExponent ε)≤(ε:ℝ)/10 := by have h := rational_binary_accuracy ε hε have he : (0:ℝ)<ε := by exact_mod_cast hε unfold accuracyExponent rw [show ε.den.bits.length+5=(ε.den.bits.length+1)+4 by omega,pow_add] norm_num nlinarith def sampleCount (n L : ℕ) (ε : ℚ) : ℕ := 10^14*(L+1)^3*n^14*⌈ε⁻¹⌉₊^2+1 lemma sampleCount_pos (n L : ℕ) (ε : ℚ) : 0 fairOutput n hn M₁ M₂ N L (bits i))) lemma amplifiedOutput_nonneg (n : ℕ) (hn : 0 0≤z) _ (by norm_num) intro z hz obtain ⟨i,rfl⟩ := List.mem_ofFn.mp hz exact fairOutput_nonneg n hn M₁ M₂ N L (bits i) lemma amplifiedOutput_zero (n : ℕ) (hn : 0 z=0) _ rfl intro z hz obtain ⟨i,rfl⟩ := List.mem_ofFn.mp hz exact fairOutput_zero n hn M₁ M₂ N L hE₂ hr hZ (bits i) theorem amplified_success (n : ℕ) (hn : 0 if relativeAccuracy ε (commonBaseCount M₁ M₂) (amplifiedOutput n hn M₁ M₂ N (annealLength n b) δ bits) then (1:ℝ) else 0) := by have hbad : uniformAverage (fun bits : FairBank n N (annealLength n b) => if outsideInterval ((1-ε)*(commonBaseCount M₁ M₂:ℚ)) ((1+ε)*(commonBaseCount M₁ M₂:ℚ)) (fairOutput n hn M₁ M₂ N (annealLength n b) bits) then (1:ℝ) else 0)≤5/16 := by have hs := fair_single_success n hn M₁ M₂ N hE₁ hE₂ hr ε hε0 hε1 b hb hN have he : (fun bits : FairBank n N (annealLength n b) => if outsideInterval ((1-ε)*(commonBaseCount M₁ M₂:ℚ)) ((1+ε)*(commonBaseCount M₁ M₂:ℚ)) (fairOutput n hn M₁ M₂ N (annealLength n b) bits) then (1:ℝ) else 0)= fun bits => 1-(if relativeAccuracy ε (commonBaseCount M₁ M₂) (fairOutput n hn M₁ M₂ N (annealLength n b) bits) then (1:ℝ) else 0) := by funext bits by_cases hh : relativeAccuracy ε (commonBaseCount M₁ M₂) (fairOutput n hn M₁ M₂ N (annealLength n b) bits) · simp only [hh,ite_true,sub_self] simp only [relativeAccuracy] at hh simp [outsideInterval,hh] · simp only [hh,ite_false,sub_zero] simp only [relativeAccuracy] at hh simp [outsideInterval,hh] rw [he,uniformAverage_one_sub] linarith have hm := median_confidence (fairOutput n hn M₁ M₂ N (annealLength n b)) ((1-ε)*(commonBaseCount M₁ M₂:ℚ)) ((1+ε)*(commonBaseCount M₁ M₂:ℚ)) δ hδ hbad convert hm using 1 congr 1 funext bits unfold relativeAccuracy amplifiedOutput split_ifs <;> rfl abbrev FPRASBank (n : ℕ) (ε δ : ℚ) := Fin (repetitionCount δ) → FairBank n (sampleCount n (annealLength n (accuracyExponent ε)) ε) (annealLength n (accuracyExponent ε)) noncomputable def boundedFPRASOutput (n : ℕ) (hn : 0 if relativeAccuracy ε (commonBaseCount M₁ M₂) (boundedFPRASOutput n hn M₁ M₂ ε δ bits) then (1:ℝ) else 0) := by constructor · intro bits exact ⟨amplifiedOutput_nonneg n hn M₁ M₂ _ _ δ bits, fun hZ => amplifiedOutput_zero n hn M₁ M₂ _ _ δ hE₂ hr hZ bits⟩ · exact amplified_success n hn M₁ M₂ _ hE₁ hE₂ hr ε δ hε0 hε1 hδ (accuracyExponent ε) (accuracyExponent_spec ε hε0) (sampleCount_spec n _ ε hε0) section GreedyOracle variable {α : Type*} [sectionInstance120 : DecidableEq α] def greedyOracle (O : Finset α → Bool) : List α → Finset α | [] => ∅ | a::l => let I := greedyOracle O l if O (insert a I) then insert a I else I lemma greedyOracle_correct (M : Matroid α) (O : Finset α → Bool) (hO : ∀ I,O I = true ↔ M.Indep (I : Set α)) (l : List α) (hE : ∀ a ∈ l,a ∈ M.E) : M.IsBasis (greedyOracle O l : Set α) (l.toFinset : Set α) := by induction l with | nil => simp [greedyOracle] | cons a l ih => have hi := ih (fun x hx => hE x (by simp [hx])) have ha := hE a (by simp) simp only [greedyOracle] split_ifs with h · have hind := (hO _).mp h apply hind.isBasis_of_subset_of_subset_closure · simpa only [List.toFinset_cons,Finset.coe_insert] using Set.insert_subset_insert hi.subset · simp only [List.toFinset_cons,Finset.coe_insert] apply Set.insert_subset · simpa only [Finset.coe_insert] using M.subset_closure _ hind.subset_ground (Finset.mem_insert_self a _) · exact hi.subset_closure.trans (M.closure_mono (by simp)) · apply hi.indep.isBasis_of_subset_of_subset_closure · exact hi.subset.trans (by simp) · simp only [List.toFinset_cons,Finset.coe_insert] apply Set.insert_subset · apply hi.indep.mem_closure_iff'.mpr refine ⟨ha,?_⟩ intro hind exfalso exact h ((hO _).mpr (by simpa using hind)) · exact hi.subset_closure def greedyQueryCount : List α → ℕ | [] => 0 | _::l => greedyQueryCount l+1 omit sectionInstance120 in lemma greedyQueryCount_eq [DecidableEq α] (l : List α) : greedyQueryCount l = l.length := by induction l <;> simp_all [greedyQueryCount] lemma greedyOracle_rank (M : Matroid α) (O : Finset α → Bool) (hO : ∀ I,O I = true ↔ M.Indep (I : Set α)) (l : List α) (hE : ∀ a ∈ l,a ∈ M.E) : (greedyOracle O l).card = (M.eRk (l.toFinset : Set α)).toNat := by have h := (greedyOracle_correct M O hO l hE).encard_eq_eRk simpa using congrArg ENat.toNat h end GreedyOracle open scoped Classical def queryFinset {n : ℕ} (O : IndependenceOracle n) (which : Bool) (I : Finset (Fin n)) : Bool := O which (fun i => decide (i ∈ I)) def rankOracle {n : ℕ} (O : IndependenceOracle n) (which : Bool) (S : Finset (Fin n)) : ℕ := (greedyOracle (queryFinset O which) ((List.finRange n).filter (fun i => decide (i ∈ S)))).card lemma queryFinset_exact {n : ℕ} (M₁ M₂ : Matroid (Fin n)) (O : IndependenceOracle n) (hO : ExactOracles M₁ M₂ O) (which : Bool) (I : Finset (Fin n)) : queryFinset O which I = true ↔ (if which then M₂ else M₁).Indep (I : Set (Fin n)) := by have h := hO which (fun i => decide (i ∈ I)) have he : {i : Fin n | decide (i ∈ I) = true} = (I : Set (Fin n)) := by ext i; simp rw [he] at h exact h lemma rankOracle_correct {n : ℕ} (M₁ M₂ : Matroid (Fin n)) (O : IndependenceOracle n) (hO : ExactOracles M₁ M₂ O) (hE₁ : M₁.E=Set.univ) (hE₂ : M₂.E=Set.univ) (which : Bool) (S : Finset (Fin n)) : rankOracle O which S = ((if which then M₂ else M₁).eRk (S : Set (Fin n))).toNat := by have hE : (if which then M₂ else M₁).E = Set.univ := by cases which <;> simpa have h := greedyOracle_rank (if which then M₂ else M₁) (queryFinset O which) (queryFinset_exact M₁ M₂ O hO which) ((List.finRange n).filter (fun i => decide (i ∈ S))) (by intro i _; simp [hE]) have hs : (((List.finRange n).filter (fun i => decide (i ∈ S))).toFinset : Set (Fin n)) = S := by ext i; simp rw [hs] at h exact h lemma rankOracle_query_bound {n : ℕ} (S : Finset (Fin n)) : greedyQueryCount ((List.finRange n).filter (fun i => decide (i ∈ S))) ≤ n := by rw [greedyQueryCount_eq] exact (List.length_filter_le _ _).trans_eq (List.length_finRange (n := n)) section SumRank open Set variable {α β : Type*} [sectionInstance121 : Fintype α] [sectionInstance122 : Fintype β] omit sectionInstance121 sectionInstance122 in lemma sum_eRk [Fintype α] [Fintype β] (M : Matroid α) (N : Matroid β) (S : Set (α ⊕ β)) : (M.sum N).eRk S = M.eRk (Sum.inl ⁻¹' S) + N.eRk (Sum.inr ⁻¹' S) := by obtain ⟨I,hI⟩ := M.exists_isBasis' (Sum.inl ⁻¹' S) obtain ⟨J,hJ⟩ := N.exists_isBasis' (Sum.inr ⁻¹' S) have hb : (M.sum N).IsBasis' (Sum.inl '' I ∪ Sum.inr '' J) S := by rw [Matroid.isBasis'_iff_isBasis_inter_ground,Matroid.sum_isBasis_iff] constructor · simpa [Set.preimage_image_eq _ Sum.inl_injective,Set.preimage_image_eq _ Sum.inr_injective] using hI.isBasis_inter_ground · simpa [Set.preimage_image_eq _ Sum.inl_injective,Set.preimage_image_eq _ Sum.inr_injective] using hJ.isBasis_inter_ground rw [hb.eRk_eq_encard,Set.encard_union_eq (Set.disjoint_image_inl_image_inr), Set.InjOn.encard_image Sum.inl_injective.injOn, Set.InjOn.encard_image Sum.inr_injective.injOn,hI.encard_eq_eRk,hJ.encard_eq_eRk] lemma dual_rank_nat (M : Matroid α) (hE : M.E=Set.univ) (S : Set α) : (M✶.eRk S).toNat+M.eRank.toNat = S.ncard+(M.eRk Sᶜ).toNat := by have h := M.eRk_dual_add_eRank S (by simp [hE]) rw [hE,← Set.compl_eq_univ_sdiff] at h have hh := congrArg ENat.toNat h rw [ENat.toNat_add (M✶.isRkFinite_set S).eRk_lt_top.ne ((M.eRank_ne_top_iff).mpr inferInstance), ENat.toNat_add (M.isRkFinite_set Sᶜ).eRk_lt_top.ne (Set.encard_ne_top_iff.mpr (Set.toFinite S))] at hh simpa only [Set.ncard,add_comm] using hh end SumRank open scoped Classical def pairedDeficiencyOracle {n : ℕ} (r : ℕ) (O : IndependenceOracle n) (Sx Sy : Finset (Fin n)) : ℕ := n+r-(rankOracle O false Sx+Sy.card+rankOracle O true Syᶜ) lemma paired_rank_nat {n r : ℕ} (M₁ M₂ : Matroid (Fin n)) (hE₂ : M₂.E=Set.univ) (hr₂ : M₂.eRank=(r:ℕ∞)) (S : Set (Fin n ⊕ Fin n)) : ((pairedMatroid M₁ M₂).eRk S).toNat+r = (M₁.eRk (Sum.inl ⁻¹' S)).toNat+(Sum.inr ⁻¹' S).ncard+ (M₂.eRk (Sum.inr ⁻¹' S)ᶜ).toNat := by rw [pairedMatroid,sum_eRk,ENat.toNat_add (M₁.isRkFinite_set _).eRk_lt_top.ne (M₂✶.isRkFinite_set _).eRk_lt_top.ne] have h := dual_rank_nat M₂ hE₂ (Sum.inr ⁻¹' S) rw [hr₂,ENat.toNat_natCast] at h omega lemma pairedDeficiencyOracle_correct {n r : ℕ} (M₁ M₂ : Matroid (Fin n)) (O : IndependenceOracle n) (hO : ExactOracles M₁ M₂ O) (hE₁ : M₁.E=Set.univ) (hE₂ : M₂.E=Set.univ) (_ : M₁.eRank=(r:ℕ∞)) (hr₂ : M₂.eRank=(r:ℕ∞)) (S : Set (Fin n ⊕ Fin n)) : pairedDeficiencyOracle r O (Sum.inl ⁻¹' S).toFinset (Sum.inr ⁻¹' S).toFinset = n-((pairedMatroid M₁ M₂).eRk S).toNat := by have h := paired_rank_nat M₁ M₂ hE₂ hr₂ S unfold pairedDeficiencyOracle rw [rankOracle_correct M₁ M₂ O hO hE₁ hE₂,rankOracle_correct M₁ M₂ O hO hE₁ hE₂] simp only [Bool.false_eq_true,ite_false,ite_true,Set.coe_toFinset,Finset.coe_compl, Set.toFinset_card,Set.fintypeCard_eq_ncard] omega def verifyCommonBase {n : ℕ} (r : ℕ) (O : IndependenceOracle n) (A : Finset (Fin n)) : Bool := decide (A.card=r) && queryFinset O false A && queryFinset O true A lemma verifyCommonBase_correct {n r : ℕ} (M₁ M₂ : Matroid (Fin n)) (O : IndependenceOracle n) (hO : ExactOracles M₁ M₂ O) (hr₁ : M₁.eRank=(r:ℕ∞)) (hr₂ : M₂.eRank=(r:ℕ∞)) (A : Finset (Fin n)) : verifyCommonBase r O A = true ↔ M₁.IsBase (A:Set (Fin n)) ∧ M₂.IsBase (A:Set (Fin n)) := by simp only [verifyCommonBase,Bool.and_eq_true,decide_eq_true_eq, queryFinset_exact M₁ M₂ O hO,Bool.false_eq_true,ite_false,ite_true] constructor · rintro ⟨⟨hc,h₁⟩,h₂⟩ have he : (A:Set (Fin n)).encard=(r:ℕ∞) := by simp [hc] constructor · apply h₁.isBase_of_eRk_ge A.finite_toSet rw [h₁.eRk_eq_encard,he,hr₁] · apply h₂.isBase_of_eRk_ge A.finite_toSet rw [h₂.eRk_eq_encard,he,hr₂] · rintro ⟨h₁,h₂⟩ refine ⟨⟨?_,h₁.indep⟩,h₂.indep⟩ have h := h₁.encard_eq_eRank rw [hr₁] at h simpa using h lemma verified_count_positive {n r : ℕ} (M₁ M₂ : Matroid (Fin n)) (O : IndependenceOracle n) (hO : ExactOracles M₁ M₂ O) (hr₁ : M₁.eRank=(r:ℕ∞)) (hr₂ : M₂.eRank=(r:ℕ∞)) (A : Finset (Fin n)) (hA : verifyCommonBase r O A=true) : 0 pairedSlots n noncomputable def oracleDeficiency (S : Set (Fin n ⊕ Fin n)) : ℕ := pairedDeficiencyOracle r O (Sum.inl ⁻¹' S).toFinset (Sum.inr ⁻¹' S).toFinset noncomputable def oracleAnneal (j : ℕ) (S : Set (Fin n ⊕ Fin n)) : ℚ := (rationalRho n^j)^(oracleDeficiency n r O S) def rationalHistoryPositive (h : List (PhaseSample n N)) : Prop := ∀ j ≤ h.length,∀ p q,0 intro hh j hj p q · have hs := hh j hj p q rw [←rationalStored_cast] exact_mod_cast hs · have hs := hh j hj p q rw [←rationalStored_cast] at hs exact_mod_cast hs noncomputable def oracleStepTree (h : List (PhaseSample n N)) (j : ℕ) : ChainIndex GS → DrawTree (ChainIndex GS) := rationalMetropolis GS (pairedSlots_fresh n) (pairedSlots_ne_nil n hn) (pairedSlots_cover n) (rationalStored n N h j) (oracleAnneal n r O j) noncomputable def oracleTraceTree (h : List (PhaseSample n N)) (j cap : ℕ) : PlainIndex GS → DrawTree (Option (PlainIndex GS)) := fun x => hittingTree (oracleStepTree n hn r O N h j) (plainPredicate GS) (cap+1) x.val noncomputable def oracleRestartTree (h : List (PhaseSample n N)) (cap : ℕ) : ℕ → DrawTree (Option (PlainIndex GS)) | 0 => letI := plainIndex_nonempty GS (pairedSlots_fresh n) (pairedSlots_cover n) (DrawTree.uniformChoice (PlainIndex GS)).map some | j+1 => (oracleRestartTree h cap j).optionBind (DrawTree.iterate (oracleTraceTree n hn r O N h (j+1) cap) (20*n^4*(n*(L+1)+2))) noncomputable def oracleStartTree (h : List (PhaseSample n N)) : DrawTree (Option (ChainIndex GS)) := (oracleRestartTree n hn r O N L h (restartCap n L) h.length).map (Option.map Subtype.val) noncomputable def oraclePhaseTree (h : List (PhaseSample n N)) : DrawTree (Option (PhaseSample n N)) := if rationalHistoryPositive n N h then (oracleStartTree n hn r O N L h).optionBind (fun x => (DrawTree.sample (oracleStepTree n hn r O N h h.length) (N-1) x).map some) else .leaf none noncomputable def oracleEstimate (h : List (PhaseSample n N)) : ℚ := (2:ℚ)^n * ∏ j ∈ Finset.range L, rationalRatio GS (fun S => rationalRho n^(oracleDeficiency n r O S)) (historySample (observedSets n N) h j) noncomputable def oracleGuard (h : List (PhaseSample n N)) (x : PlainIndex GS) : ℚ := if oracleDeficiency n r O x.val.val=0 then oracleEstimate n r O N L h else 0 noncomputable def oracleWitnessTree (h : List (PhaseSample n N)) : DrawTree (Option (PlainIndex GS)) := if rationalHistoryPositive n N h then oracleRestartTree n hn r O N L h (restartCap n L) h.length else .leaf none noncomputable def oracleAlgorithmTree : DrawTree (Option ℚ) := (DrawTree.history (oraclePhaseTree n hn r O N L) L []).optionBind (fun h => (oracleWitnessTree n hn r O N L h).map (Option.map (oracleGuard n r O N L h))) variable (M₁ M₂ : Matroid (Fin n)) (hO : ExactOracles M₁ M₂ O) variable (hE₁ : M₁.E=Set.univ) (hE₂ : M₂.E=Set.univ) variable (hr₁ : M₁.eRank=(r:ℕ∞)) (hr₂ : M₂.eRank=(r:ℕ∞)) include hO hE₁ hE₂ hr₁ hr₂ lemma oracleDeficiency_eq (S : Set (Fin n ⊕ Fin n)) : oracleDeficiency n r O S=n-((pairedMatroid M₁ M₂).eRk S).toNat := pairedDeficiencyOracle_correct M₁ M₂ O hO hE₁ hE₂ hr₁ hr₂ S lemma oracleAnneal_eq (j : ℕ) : oracleAnneal n r O j = rationalAnneal (pairedMatroid M₁ M₂) n j := by funext S simp only [oracleAnneal,rationalAnneal,oracleDeficiency_eq n r O M₁ M₂ hO hE₁ hE₂ hr₁ hr₂] lemma oracleStepTree_eq (h : List (PhaseSample n N)) (j : ℕ) : oracleStepTree n hn r O N h j=actualStepTree n hn (pairedMatroid M₁ M₂) N h j := by unfold oracleStepTree actualStepTree rw [oracleAnneal_eq n r O M₁ M₂ hO hE₁ hE₂ hr₁ hr₂] lemma oracleTraceTree_eq (h : List (PhaseSample n N)) (j cap : ℕ) : oracleTraceTree n hn r O N h j cap=actualTraceTree n hn (pairedMatroid M₁ M₂) N h j cap := by unfold oracleTraceTree actualTraceTree rw [oracleStepTree_eq n hn r O N M₁ M₂ hO hE₁ hE₂ hr₁ hr₂] lemma oracleRestartTree_eq (h : List (PhaseSample n N)) (cap j : ℕ) : oracleRestartTree n hn r O N L h cap j = actualRestartTree n hn (pairedMatroid M₁ M₂) N L h cap j := by induction j with | zero => rfl | succ j ih => simp only [oracleRestartTree,actualRestartTree,ih, oracleTraceTree_eq n hn r O N M₁ M₂ hO hE₁ hE₂ hr₁ hr₂] lemma oracleStartTree_eq (h : List (PhaseSample n N)) : oracleStartTree n hn r O N L h=actualStartTree n hn (pairedMatroid M₁ M₂) N L h := by unfold oracleStartTree actualStartTree rw [oracleRestartTree_eq n hn r O N L M₁ M₂ hO hE₁ hE₂ hr₁ hr₂] lemma oraclePhaseTree_eq : oraclePhaseTree n hn r O N L=actualPhaseTree n hn (pairedMatroid M₁ M₂) N L := by funext h simp only [oraclePhaseTree,actualPhaseTree,rationalHistoryPositive_iff, oracleStartTree_eq n hn r O N L M₁ M₂ hO hE₁ hE₂ hr₁ hr₂, oracleStepTree_eq n hn r O N M₁ M₂ hO hE₁ hE₂ hr₁ hr₂] lemma oracleEstimate_eq (h : List (PhaseSample n N)) : oracleEstimate n r O N L h=rationalEstimate n M₁ M₂ N L h := by simp only [oracleEstimate,rationalEstimate, oracleDeficiency_eq n r O M₁ M₂ hO hE₁ hE₂ hr₁ hr₂] lemma oracleGuard_eq (h : List (PhaseSample n N)) : oracleGuard n r O N L h=rationalGuard n M₁ M₂ N L h := by funext x simp only [oracleGuard,rationalGuard,Witnessed, oracleDeficiency_eq n r O M₁ M₂ hO hE₁ hE₂ hr₁ hr₂, oracleEstimate_eq n r O N L M₁ M₂ hO hE₁ hE₂ hr₁ hr₂] split_ifs <;> simp_all lemma oracleWitnessTree_eq (h : List (PhaseSample n N)) : oracleWitnessTree n hn r O N L h=rationalWitnessTree n hn M₁ M₂ N L h := by simp only [oracleWitnessTree,rationalWitnessTree,rationalHistoryPositive_iff, oracleRestartTree_eq n hn r O N L M₁ M₂ hO hE₁ hE₂ hr₁ hr₂] theorem oracleAlgorithmTree_eq : oracleAlgorithmTree n hn r O N L=rationalAlgorithmTree n hn M₁ M₂ N L := by simp only [oracleAlgorithmTree,rationalAlgorithmTree, oraclePhaseTree_eq n hn r O N L M₁ M₂ hO hE₁ hE₂ hr₁ hr₂, oracleWitnessTree_eq n hn r O N L M₁ M₂ hO hE₁ hE₂ hr₁ hr₂, oracleGuard_eq n r O N L M₁ M₂ hO hE₁ hE₂ hr₁ hr₂] end section open scoped BigOperators Classical lemma RatBound.add {q r : ℚ} {B D : ℕ} (hq : RatBound q B) (hr : RatBound r D) : RatBound (q+r) (2*B*D) := by obtain ⟨a,b,ha,hb,hb0,rfl⟩ := hq obtain ⟨c,d,hc,hd,hd0,rfl⟩ := hr refine ⟨a*d+c*b,b*d,?_,?_,Nat.mul_pos hb0 hd0,?_⟩ · nlinarith [Nat.mul_le_mul ha hd,Nat.mul_le_mul hc hb] · nlinarith [Nat.mul_le_mul hb hd] · push_cast have hbq : (b:ℚ)≠0 := by exact_mod_cast Nat.ne_of_gt hb0 have hdq : (d:ℚ)≠0 := by exact_mod_cast Nat.ne_of_gt hd0 field_simp lemma RatBound.bits {q : ℚ} {H : ℕ} (hq : RatBound q (2^H)) : q.num.natAbs.bits.length ≤ H+1 ∧ q.den.bits.length ≤ H+1 := by constructor · rw [Nat.size_eq_bits_len] exact (Nat.size_le_size hq.num_le).trans_eq (Nat.size_pow (n := H)) · rw [Nat.size_eq_bits_len] exact (Nat.size_le_size hq.den_le).trans_eq (Nat.size_pow (n := H)) lemma RatBound.binary_add {q r : ℚ} {H J : ℕ} (hq : RatBound q (2^H)) (hr : RatBound r (2^J)) : RatBound (q+r) (2^(H+J+1)) := by convert hq.add hr using 1 simp only [pow_add,pow_one] ring lemma RatBound.binary_mul {q r : ℚ} {H J : ℕ} (hq : RatBound q (2^H)) (hr : RatBound r (2^J)) : RatBound (q*r) (2^(H+J)) := by simpa only [pow_add] using hq.mul hr lemma RatBound.binary_div {q r : ℚ} {H J : ℕ} (hq : RatBound q (2^H)) (hr : RatBound r (2^J)) : RatBound (q/r) (2^(H+J)) := by simpa only [pow_add] using hq.div hr lemma RatBound.binary_list_sum {X : Type*} (f : X → ℚ) (l : List X) (H : ℕ) (h : ∀ x∈l,RatBound (f x) (2^H)) : RatBound ((l.map f).sum) (2^((H+1)*l.length)) := by induction l with | nil => simpa using RatBound.zero 1 (by decide) | cons x l ih => have hx := h x (by simp) have ht := ih (fun y hy => h y (by simp [hy])) simpa only [List.map_cons,List.sum_cons,List.length_cons,Nat.mul_add,Nat.mul_one, show H + (H+1)*l.length+1=(H+1)*l.length+(H+1) by omega] using hx.binary_add ht lemma RatBound.binary_prod {X : Type*} (s : Finset X) (f : X → ℚ) (H : ℕ) (h : ∀ x∈s,RatBound (f x) (2^H)) : RatBound (∏ x∈s,f x) (2^(H*s.card)) := by induction s using Finset.induction_on with | empty => simpa using RatBound.one 1 (by decide) | @insert x s hx ih => have hh := (h x (by simp)).binary_mul (ih (fun y hy => h y (by simp [hy]))) simpa only [Finset.prod_insert hx,Finset.card_insert_of_notMem hx,Nat.mul_add,Nat.mul_one, add_comm H (H*s.card)] using hh lemma rationalEmpirical_binary_bound {Γ : Type*} (f : Set Γ → ℚ) (l : List (Set Γ)) (N H : ℕ) (hlen : l.length≤N) (hf : ∀ S∈l,RatBound (f S) (2^H)) : RatBound (rationalEmpirical f l) (2^((H+2)*N)) := by have hs := RatBound.binary_list_sum f l H hf have hnat : RatBound (l.length:ℚ) (2^N) := RatBound.nat _ _ (hlen.trans (Nat.le_of_lt (Nat.lt_two_pow_self))) (by positivity) apply (hs.binary_div hnat).mono apply Nat.pow_le_pow_right (by decide : 0<2) nlinarith lemma rho_observable_binary (n : ℕ) (hn : 0 1) S) (2^0) := by intro S hS; unfold rationalPlain; split_ifs · exact RatBound.one 1 (by decide) · exact RatBound.zero 1 (by decide) have hh := (rationalEmpirical_binary_bound _ l N H hlen hf').binary_div (rationalEmpirical_binary_bound _ l N 0 hlen hi) unfold rationalRatio apply hh.mono apply Nat.pow_le_pow_right (by decide : 0<2) nlinarith variable (n : ℕ) (hn : 0 simp | some x => simpa only [Option.map_some,Option.getD_some] using (observedSets_length n N hN x).le def outputWordBound (n N L : ℕ) : ℕ := n+(2*n*n+5)*N*L include hn hN in lemma rationalEstimate_binary_bound (h : List (PhaseSample n N)) : RatBound (rationalEstimate n M₁ M₂ N L h) (2^(outputWordBound n N L)) := by have hp : RatBound ((2:ℚ)^n) (2^n) := by exact_mod_cast (RatBound.nat (2^n) (2^n) le_rfl (by positivity)) have hh := RatBound.binary_prod (Finset.range L) (fun j => rationalRatio (pairedSlots n) (fun S => rationalRho n^(n-((pairedMatroid M₁ M₂).eRk S).toNat)) (historySample (observedSets n N) h j)) ((2*n*n+5)*N) (by intro j hj exact rationalRatio_binary_bound _ _ _ N (2*n*n) (historySample_length_le n N hN h j) (fun S => rho_observable_binary n hn _ (Nat.sub_le n _))) simpa only [rationalEstimate,Finset.card_range,outputWordBound] using hp.binary_mul hh include hn hN in lemma rationalGuard_binary_bound (h : List (PhaseSample n N)) (x : PlainIndex (pairedSlots n)) : RatBound (rationalGuard n M₁ M₂ N L h x) (2^(outputWordBound n N L)) := by unfold rationalGuard split_ifs · exact rationalEstimate_binary_bound n hn M₁ M₂ N L hN h · exact RatBound.zero _ (by positivity) end def bitResourceParameter (n : ℕ) (ε δ : ℚ) : ℕ := 1+n+ε.den.bits.length+δ.den.bits.length+⌈ε⁻¹⌉₊ def fairBitCount (n : ℕ) (ε δ : ℚ) : ℕ := let L := annealLength n (accuracyExponent ε) let N := sampleCount n L ε repetitionCount δ * drawWordBound n N L * (algorithmDrawBound n N L+6) * algorithmDrawBound n N L lemma polynomial_recipe_bounds (n e f E T : ℕ) (hT : 0 oracleFairOutput n hn r O N L (bits i))) noncomputable def oracleBoundedOutput (n r : ℕ) (O : IndependenceOracle n) (ε δ : ℚ) (bits : FPRASBank n ε δ) : ℚ := if hn : 0 if relativeAccuracy ε (commonBaseCount M₁ M₂) (oracleBoundedOutput n r O ε δ bits) then (1:ℝ) else 0) := by by_cases hn : 0 linarith simpa only [ho,commonBaseCount_empty,relativeAccuracy,Nat.cast_one,mul_one,ite_eq_left hac, uniformAverage_const] using (sub_le_self (1:ℝ) (by exact_mod_cast hδ.le : (0:ℝ)≤δ)) open scoped BigOperators Classical noncomputable def wordPlainEquiv (n : ℕ) : BitWord n ≃ PlainIndex (pairedSlots n) where toFun b := ⟨⟨transversal {i | b i=true},Or.inl (transversal_plain n _)⟩,transversal_plain n _⟩ invFun S := fun i => decide (Sum.inl i∈S.val.val) left_inv b := by funext i change decide (Sum.inl i∈transversal {i | b i=true})=b i change decide (i∈Sum.inl ⁻¹' transversal {i | b i=true})=b i rw [preimage_inl_transversal] cases h : b i <;> simp [h] right_inv S := by apply Subtype.ext apply Subtype.ext change transversal {i | decide (Sum.inl i∈S.val.val)=true}=S.val.val have he : {i | decide (Sum.inl i∈S.val.val)=true}=Sum.inl ⁻¹' S.val.val := by ext i simp rw [he] exact (plain_eq_transversal n S.val.val S.property).symm noncomputable def sortedMemberEquiv {Γ : Type*} [Fintype Γ] [LinearOrder Γ] (S : Set Γ) : Fin (Fintype.card S) ≃ S := by let c : ↥S.toFinset ≃ S := { toFun := fun a => ⟨a.val,Set.mem_toFinset.mp a.property⟩ invFun := fun a => ⟨a.val,Set.mem_toFinset.mpr a.property⟩ left_inv := by intro a; rfl right_inv := by intro a; rfl } let e := (S.toFinset.orderIsoOfFin rfl).toEquiv.trans c have he : Fintype.card S=S.toFinset.card := by simpa only [Fintype.card_fin] using (Fintype.card_congr e).symm exact (finCongr he).trans e noncomputable def canonicalPlainEnumeration (n : ℕ) : Fin (Fintype.card (PlainIndex (pairedSlots n))) ≃ PlainIndex (pairedSlots n) := (finCongr (plainIndex_card n)).trans ((wordEquiv n).symm.trans (wordPlainEquiv n)) noncomputable def canonicalExchangeEnumeration (n : ℕ) (S : Set (Fin n ⊕ Fin n)) : Fin (Fintype.card (ExchangeChoice S)) ≃ ExchangeChoice S := by letI : LinearOrder (Fin n ⊕ Fin n) := LinearOrder.lift' (finSumFinEquiv : Fin n ⊕ Fin n ≃ Fin (n+n)) (Equiv.injective _) let e := finProdFinEquiv.symm.trans ((sortedMemberEquiv S).prodCongr (sortedMemberEquiv Sᶜ)) have he : Fintype.card (ExchangeChoice S)=_ := (Fintype.card_congr e).symm exact (finCongr (by simpa only [Fintype.card_fin] using he)).trans e section namespace DrawTree open scoped BigOperators Classical variable {A B : Type*} inductive Reindexed : DrawTree A → DrawTree A → Prop | leaf (a : A) : Reindexed (.leaf a) (.leaf a) | draw (v : ℕ) (k l : Fin (v+1) → DrawTree A) (e : Fin (v+1) ≃ Fin (v+1)) (h : ∀ i,Reindexed (k i) (l (e i))) : Reindexed (.draw v k) (.draw v l) lemma Reindexed.refl (t : DrawTree A) : Reindexed t t := by induction t with | leaf a => exact .leaf a | draw v k ih => exact .draw v k k (Equiv.refl _) ih lemma Reindexed.symm {t u : DrawTree A} (h : Reindexed t u) : Reindexed u t := by induction h with | leaf a => exact .leaf a | draw v k l e h ih => apply Reindexed.draw v l k e.symm intro i simpa using ih (e.symm i) lemma Reindexed.bind {t u : DrawTree A} {k l : A → DrawTree B} (ht : Reindexed t u) (hk : ∀ a,Reindexed (k a) (l a)) : Reindexed (t.bind k) (u.bind l) := by induction ht with | leaf a => exact hk a | draw v a b e h ih => exact .draw v _ _ e ih lemma Reindexed.map {t u : DrawTree A} (h : Reindexed t u) (f : A → B) : Reindexed (t.map f) (u.map f) := h.bind (fun a => .leaf (f a)) lemma Reindexed.expectation {t u : DrawTree A} (h : Reindexed t u) (φ : A → ℝ) : t.expectation φ=u.expectation φ := by induction h with | leaf a => rfl | draw v k l e h ih => change uniformAverage (fun i => (k i).expectation φ)=uniformAverage (fun i => (l i).expectation φ) simp_rw [ih] exact uniformAverage_equiv e (fun i => (l i).expectation φ) noncomputable def uniformVia (A : Type*) [Fintype A] [Nonempty A] (e : Fin (Fintype.card A) ≃ A) : DrawTree A := let h : Fintype.card A-1+1=Fintype.card A := by have hh := Fintype.card_pos (α := A); omega .draw (Fintype.card A-1) (fun i => .leaf (e (Fin.cast h i))) lemma uniformVia_reindexed (A : Type*) [Fintype A] [Nonempty A] (e : Fin (Fintype.card A) ≃ A) : Reindexed (uniformVia A e) (uniformChoice A) := by let h : Fintype.card A-1+1=Fintype.card A := by have hh := Fintype.card_pos (α := A); omega let c := finCongr h let p := c.trans (e.trans ((Fintype.equivFin A).trans c.symm)) apply Reindexed.draw _ _ _ p intro i have he : (Fintype.equivFin A).symm (Fin.cast h (p i))=e (Fin.cast h i) := by simp [p,c] simpa only [he] using Reindexed.leaf (e (Fin.cast h i)) lemma Reindexed.fits {t u : DrawTree A} (h : Reindexed t u) (H M : ℕ) (ht : Fits H M t) : Fits H M u := by induction h generalizing M with | leaf a => trivial | draw v k l e h ih => cases M with | zero => exact False.elim ht | succ M => refine ⟨ht.1,fun i => ?_⟩ simpa using ih (e.symm i) M (ht.2 (e.symm i)) lemma Reindexed.all {t u : DrawTree A} (h : Reindexed t u) (P : A → Prop) (ht : All P t) : All P u := by induction h with | leaf a => exact ht | draw v k l e h ih => intro i simpa using ih (e.symm i) (ht (e.symm i)) lemma Reindexed.run_expectation {t u : DrawTree A} (h : Reindexed t u) (H D M : ℕ) (ht : Fits H M t) (φ : A → ℝ) : uniformAverage (fun bits => optionValue φ (run H D M t bits))= uniformAverage (fun bits => optionValue φ (run H D M u bits)) := by induction h generalizing M with | leaf a => rfl | draw v k l e h ih => cases M with | zero => exact False.elim ht | succ M => rw [run_draw_average H D M v k ht.1 φ,run_draw_average H D M v l ht.1 φ] congr 1 have he : ∀ i,uniformAverage (fun bits => optionValue φ (run H D M (k i) bits))= uniformAverage (fun bits => optionValue φ (run H D M (l (e i)) bits)) := fun i => ih i M (ht.2 i) simp_rw [he] exact uniformAverage_equiv e (fun i => uniformAverage (fun bits => optionValue φ (run H D M (l i) bits))) lemma Reindexed.run_observable {t u : DrawTree A} (h : Reindexed t u) (H D M : ℕ) (ht : Fits H M t) (φ : Option A → ℝ) : uniformAverage (fun bits => φ (run H D M t bits))= uniformAverage (fun bits => φ (run H D M u bits)) := by have hf : ∀ x : Option A,φ x=optionValue (fun a => φ (some a)-φ none) x+φ none := by intro x; cases x <;> simp [optionValue] have he (v : DrawTree A) : (fun bits => φ (run H D M v bits))= (fun bits => optionValue (fun a => φ (some a)-φ none) (run H D M v bits)+φ none) := funext (fun bits => hf _) rw [he t,he u,uniformAverage_add,uniformAverage_add,h.run_expectation H D M ht] lemma Reindexed.optionBind {t u : DrawTree (Option A)} {k l : A → DrawTree (Option B)} (ht : Reindexed t u) (hk : ∀ a,Reindexed (k a) (l a)) : Reindexed (t.optionBind k) (u.optionBind l) := by apply ht.bind intro a; cases a with | none => exact .leaf none | some a => exact hk a lemma Reindexed.iterate {t u : A → DrawTree (Option A)} (h : ∀ a,Reindexed (t a) (u a)) (k : ℕ) (a : A) : Reindexed (iterate t k a) (iterate u k a) := by induction k with | zero => exact .leaf (some a) | succ k ih => exact ih.optionBind h lemma Reindexed.sample [Fintype A] {t u : A → DrawTree A} (h : ∀ a,Reindexed (t a) (u a)) (k : ℕ) (a : A) : Reindexed (sample t k a) (sample u k a) := by induction k generalizing a with | zero => exact .leaf a | succ k ih => exact (h a).bind (fun x => (ih x).map (fun v => (a,v))) lemma Reindexed.history {K L : List A → DrawTree (Option A)} (h : ∀ a,Reindexed (K a) (L a)) (k : ℕ) (a : List A) : Reindexed (history K k a) (history L k a) := by induction k generalizing a with | zero => exact .leaf (some a) | succ k ih => exact (h a).optionBind (fun x => ih (a++[x])) end DrawTree lemma hittingTree_reindexed {X : Type*} [Fintype X] {t u : X → DrawTree X} (h : ∀ x,DrawTree.Reindexed (t x) (u x)) (A : X → Prop) (k : ℕ) (x : X) : DrawTree.Reindexed (hittingTree t A k x) (hittingTree u A k x) := by classical induction k generalizing x with | zero => exact .leaf none | succ k ih => apply (h x).bind intro y by_cases hy : A y · simp only [dite_eq_left hy]; exact .leaf _ · simp only [dite_eq_right hy]; exact ih y open scoped BigOperators Classical variable (n : ℕ) (hn : 0 pairedSlots n noncomputable def canonicalMetropolis (w : ((Fin n ⊕ Fin n) × (Fin n ⊕ Fin n)) → ((Fin n ⊕ Fin n) × (Fin n ⊕ Fin n)) → ℚ) (f : Set (Fin n ⊕ Fin n) → ℚ) (S : ChainIndex GS) : DrawTree (ChainIndex GS) := letI : Nonempty (ExchangeChoice S.val) := Fintype.card_pos_iff.mp (by rw [exchangeChoice_card GS (pairedSlots_fresh n) (pairedSlots_cover n),pairedSlots_length]; positivity) (DrawTree.bernoulli (1/2)).bind (fun lazy => if lazy then .leaf S else (DrawTree.uniformVia (ExchangeChoice S.val) (canonicalExchangeEnumeration n S.val)).bind (rationalExchange GS w f S)) lemma canonicalMetropolis_reindexed (w : ((Fin n ⊕ Fin n) × (Fin n ⊕ Fin n)) → ((Fin n ⊕ Fin n) × (Fin n ⊕ Fin n)) → ℚ) (f : Set (Fin n ⊕ Fin n) → ℚ) (S : ChainIndex GS) : DrawTree.Reindexed (canonicalMetropolis n hn w f S) (rationalMetropolis GS (pairedSlots_fresh n) (pairedSlots_ne_nil n hn) (pairedSlots_cover n) w f S) := by let : Nonempty (ExchangeChoice S.val) := Fintype.card_pos_iff.mp (by rw [exchangeChoice_card GS (pairedSlots_fresh n) (pairedSlots_cover n),pairedSlots_length]; positivity) apply (DrawTree.Reindexed.refl (DrawTree.bernoulli (1/2))).bind intro lazy cases lazy with | true => exact .leaf S | false => apply (DrawTree.uniformVia_reindexed _ (canonicalExchangeEnumeration n S.val)).bind intro a; exact .refl _ noncomputable def canonicalStepTree (h : List (PhaseSample n N)) (j : ℕ) : ChainIndex GS → DrawTree (ChainIndex GS) := canonicalMetropolis n hn (rationalStored n N h j) (oracleAnneal n r O j) noncomputable def canonicalTraceTree (h : List (PhaseSample n N)) (j cap : ℕ) : PlainIndex GS → DrawTree (Option (PlainIndex GS)) := fun x => hittingTree (canonicalStepTree n hn r O N h j) (plainPredicate GS) (cap+1) x.val noncomputable def canonicalRestartTree (h : List (PhaseSample n N)) (cap : ℕ) : ℕ → DrawTree (Option (PlainIndex GS)) | 0 => letI := plainIndex_nonempty GS (pairedSlots_fresh n) (pairedSlots_cover n) (DrawTree.uniformVia (PlainIndex GS) (canonicalPlainEnumeration n)).map some | j+1 => (canonicalRestartTree h cap j).optionBind (DrawTree.iterate (canonicalTraceTree n hn r O N h (j+1) cap) (20*n^4*(n*(L+1)+2))) noncomputable def canonicalStartTree (h : List (PhaseSample n N)) : DrawTree (Option (ChainIndex GS)) := (canonicalRestartTree n hn r O N L h (restartCap n L) h.length).map (Option.map Subtype.val) noncomputable def canonicalPhaseTree (h : List (PhaseSample n N)) : DrawTree (Option (PhaseSample n N)) := if rationalHistoryPositive n N h then (canonicalStartTree n hn r O N L h).optionBind (fun x => (DrawTree.sample (canonicalStepTree n hn r O N h h.length) (N-1) x).map some) else .leaf none noncomputable def canonicalWitnessTree (h : List (PhaseSample n N)) : DrawTree (Option (PlainIndex GS)) := if rationalHistoryPositive n N h then canonicalRestartTree n hn r O N L h (restartCap n L) h.length else .leaf none noncomputable def canonicalAlgorithmTree : DrawTree (Option ℚ) := (DrawTree.history (canonicalPhaseTree n hn r O N L) L []).optionBind (fun h => (canonicalWitnessTree n hn r O N L h).map (Option.map (oracleGuard n r O N L h))) lemma canonicalStepTree_reindexed (h : List (PhaseSample n N)) (j : ℕ) (S : ChainIndex GS) : DrawTree.Reindexed (canonicalStepTree n hn r O N h j S) (oracleStepTree n hn r O N h j S) := canonicalMetropolis_reindexed n hn _ _ S lemma canonicalTraceTree_reindexed (h : List (PhaseSample n N)) (j cap : ℕ) (S : PlainIndex GS) : DrawTree.Reindexed (canonicalTraceTree n hn r O N h j cap S) (oracleTraceTree n hn r O N h j cap S) := hittingTree_reindexed (canonicalStepTree_reindexed n hn r O N h j) _ _ _ lemma canonicalRestartTree_reindexed (h : List (PhaseSample n N)) (cap j : ℕ) : DrawTree.Reindexed (canonicalRestartTree n hn r O N L h cap j) (oracleRestartTree n hn r O N L h cap j) := by let := plainIndex_nonempty GS (pairedSlots_fresh n) (pairedSlots_cover n) induction j with | zero => exact (DrawTree.uniformVia_reindexed _ (canonicalPlainEnumeration n)).map some | succ j ih => exact ih.optionBind (fun S => DrawTree.Reindexed.iterate (canonicalTraceTree_reindexed n hn r O N h (j+1) cap) _ S) lemma canonicalStartTree_reindexed (h : List (PhaseSample n N)) : DrawTree.Reindexed (canonicalStartTree n hn r O N L h) (oracleStartTree n hn r O N L h) := (canonicalRestartTree_reindexed n hn r O N L h _ _).map _ lemma canonicalPhaseTree_reindexed (h : List (PhaseSample n N)) : DrawTree.Reindexed (canonicalPhaseTree n hn r O N L h) (oraclePhaseTree n hn r O N L h) := by unfold canonicalPhaseTree oraclePhaseTree split_ifs · exact (canonicalStartTree_reindexed n hn r O N L h).optionBind (fun S => (DrawTree.Reindexed.sample (canonicalStepTree_reindexed n hn r O N h h.length) _ S).map some) · exact .leaf none lemma canonicalWitnessTree_reindexed (h : List (PhaseSample n N)) : DrawTree.Reindexed (canonicalWitnessTree n hn r O N L h) (oracleWitnessTree n hn r O N L h) := by unfold canonicalWitnessTree oracleWitnessTree split_ifs · exact canonicalRestartTree_reindexed n hn r O N L h _ _ · exact .leaf none lemma canonicalAlgorithmTree_reindexed : DrawTree.Reindexed (canonicalAlgorithmTree n hn r O N L) (oracleAlgorithmTree n hn r O N L) := (DrawTree.Reindexed.history (canonicalPhaseTree_reindexed n hn r O N L) L []).optionBind (fun h => (canonicalWitnessTree_reindexed n hn r O N L h).map _) end section CanonicalFair open scoped BigOperators Classical lemma uniformAverage_independent_eq {X Y Z : Type*} [Fintype X] [Fintype Y] (f : X → Z) (g : Y → Z) (h : ∀ φ : Z → ℝ,uniformAverage (fun x => φ (f x))=uniformAverage (fun y => φ (g y))) (k : ℕ) (F : (Fin k → Z) → ℝ) : uniformAverage (fun xs : Fin k → X => F (fun i => f (xs i)))= uniformAverage (fun ys : Fin k → Y => F (fun i => g (ys i))) := by induction k with | zero => have hf : ∀ xs : Fin 0 → X,(fun i => f (xs i))=(fun i : Fin 0 => Fin.elim0 i) := by intro xs; funext i; exact Fin.elim0 i have hg : ∀ ys : Fin 0 → Y,(fun i => g (ys i))=(fun i : Fin 0 => Fin.elim0 i) := by intro ys; funext i; exact Fin.elim0 i simp_rw [hf,hg,uniformAverage_const] | succ k ih => have hf (x : X) (xs : Fin k → X) : (fun i : Fin (k+1) => f ((Fin.cons x xs : Fin (k+1) → X) i))=Fin.cons (f x) (fun i => f (xs i)) := by funext i; refine Fin.cases ?_ (fun j => ?_) i <;> rfl have hg (y : Y) (ys : Fin k → Y) : (fun i : Fin (k+1) => g ((Fin.cons y ys : Fin (k+1) → Y) i))=Fin.cons (g y) (fun i => g (ys i)) := by funext i; refine Fin.cases ?_ (fun j => ?_) i <;> rfl rw [uniformAverage_fin_succ,uniformAverage_fin_succ] simp_rw [hf,hg] have hi (x : X) := ih (fun zs => F (Fin.cons (f x) zs)) simp_rw [hi] exact h (fun z => uniformAverage (fun ys : Fin k → Y => F (Fin.cons z (fun i => g (ys i))))) noncomputable def canonicalFairOutput (n : ℕ) (hn : 0 canonicalFairOutput n hn r O N L (bits i))) noncomputable def canonicalBoundedOutput (n r : ℕ) (O : IndependenceOracle n) (ε δ : ℚ) (bits : FPRASBank n ε δ) : ℚ := if hn : 0 simp | some a => cases a with | none => simp | some z => simp only [Option.join_some,Option.getD_some] have hz := DrawTree.run_all _ _ _ _ _ ht bits (some z) he z rfl exact ⟨hz.1,hz.2 hE₂ (hr₁.trans hr₂.symm)⟩ include hO hE₁ hE₂ hr₁ hr₂ in lemma canonicalFairOutput_law (hN : 0 φ (canonicalFairOutput n hn r O N L bits))= uniformAverage (fun bits : FairBank n N L => φ (fairOutput n hn M₁ M₂ N L bits)) := (canonicalAlgorithmTree_to_rational n hn r O N L M₁ M₂ hO hE₁ hE₂ hr₁ hr₂).run_observable _ _ _ (canonicalAlgorithmTree_fits n hn r O N L M₁ M₂ hO hE₁ hE₂ hr₁ hr₂ hN) (fun a : Option (Option ℚ) => φ (a.join.getD 0)) include hO hE₁ hE₂ hr₁ hr₂ in lemma canonicalAmplifiedOutput_law (hN : 0 φ (canonicalAmplifiedOutput n hn r O N L δ bits))= uniformAverage (fun bits => φ (amplifiedOutput n hn M₁ M₂ N L δ bits)) := uniformAverage_independent_eq (canonicalFairOutput n hn r O N L) (fairOutput n hn M₁ M₂ N L) (canonicalFairOutput_law n hn r O N L M₁ M₂ hO hE₁ hE₂ hr₁ hr₂ hN) _ (fun z => φ (rationalMedian (List.ofFn z))) include hO hE₁ hE₂ hr₁ hr₂ in lemma canonicalAmplifiedOutput_all (δ : ℚ) (bits : Fin (repetitionCount δ) → FairBank n N L) : 0≤canonicalAmplifiedOutput n hn r O N L δ bits ∧ (commonBaseCount M₁ M₂=0 → canonicalAmplifiedOutput n hn r O N L δ bits=0) := by constructor · apply rationalMedian_all (fun z => 0≤z) _ (by norm_num) intro z hz obtain ⟨i,rfl⟩ := List.mem_ofFn.mp hz exact (canonicalFairOutput_all n hn r O N L M₁ M₂ hO hE₁ hE₂ hr₁ hr₂ (bits i)).1 · intro hZ apply rationalMedian_all (fun z => z=0) _ rfl intro z hz obtain ⟨i,rfl⟩ := List.mem_ofFn.mp hz exact (canonicalFairOutput_all n hn r O N L M₁ M₂ hO hE₁ hE₂ hr₁ hr₂ (bits i)).2 hZ end CanonicalFair open scoped BigOperators Classical theorem canonical_bounded_fair_experiment (n r : ℕ) (O : IndependenceOracle n) (M₁ M₂ : Matroid (Fin n)) (hO : ExactOracles M₁ M₂ O) (hE₁ : M₁.E=Set.univ) (hE₂ : M₂.E=Set.univ) (hr₁ : M₁.eRank=(r:ℕ∞)) (hr₂ : M₂.eRank=(r:ℕ∞)) (ε δ : ℚ) (hε0 : 0<ε) (hε1 : ε<1) (hδ : 0<δ) : (∀ bits : FPRASBank n ε δ,0≤canonicalBoundedOutput n r O ε δ bits ∧ (commonBaseCount M₁ M₂=0 → canonicalBoundedOutput n r O ε δ bits=0)) ∧ 1-(δ:ℝ)≤uniformAverage (fun bits : FPRASBank n ε δ => if relativeAccuracy ε (commonBaseCount M₁ M₂) (canonicalBoundedOutput n r O ε δ bits) then (1:ℝ) else 0) := by by_cases hn : 0 if relativeAccuracy ε (commonBaseCount M₁ M₂) z then (1:ℝ) else 0) rw [hlaw] exact (bounded_fair_experiment n hn M₁ M₂ hE₁ hE₂ (hr₁.trans hr₂.symm) ε δ hε0 hε1 hδ).2 · have hn0 : n=0 := by omega subst n have ho : ∀ bits : FPRASBank 0 ε δ,canonicalBoundedOutput 0 r O ε δ bits=1 := by intro bits; simp [canonicalBoundedOutput] constructor · intro bits rw [ho bits,commonBaseCount_empty] norm_num · have hac : 1-ε≤(1:ℚ) ∧ (1:ℚ)≤1+ε := by constructor <;> linarith simpa only [ho,commonBaseCount_empty,relativeAccuracy,Nat.cast_one,mul_one,ite_eq_left hac, uniformAverage_const] using (sub_le_self (1:ℝ) (by exact_mod_cast hδ.le : (0:ℝ)≤δ)) open scoped BigOperators Classical def bitMatrixEquiv (a b : ℕ) : BitWord (a*b) ≃ (Fin a → BitWord b) := (Equiv.arrowCongr finProdFinEquiv.symm (Equiv.refl Bool)).trans (Equiv.curry (Fin a) (Fin b) Bool) def fourBitEquiv (a b c d : ℕ) : BitWord (a*(b*(c*d))) ≃ (Fin a → Fin b → Fin c → BitWord d) := (bitMatrixEquiv a (b*(c*d))).trans (Equiv.piCongrRight (fun _ => (bitMatrixEquiv b (c*d)).trans (Equiv.piCongrRight (fun _ => bitMatrixEquiv c d)))) def bankWordEquiv (n : ℕ) (ε δ : ℚ) : BitWord (fairBitCount n ε δ) ≃ FPRASBank n ε δ := by let L := annealLength n (accuracyExponent ε) let N := sampleCount n L ε let M := algorithmDrawBound n N L let H := drawWordBound n N L let R := repetitionCount δ have h : fairBitCount n ε δ=R*(M*((M+6)*H)) := by dsimp [fairBitCount,R,M,H,N,L]; ring exact (Equiv.arrowCongr (finCongr h) (Equiv.refl Bool)).trans (fourBitEquiv R M (M+6) H) noncomputable def flatFPRASOutput (n r : ℕ) (O : IndependenceOracle n) (ε δ : ℚ) (bits : BitWord (fairBitCount n ε δ)) : ℚ := canonicalBoundedOutput n r O ε δ (bankWordEquiv n ε δ bits) noncomputable def paddedFPRASOutput (n r : ℕ) (O : IndependenceOracle n) (ε δ : ℚ) (B : ℕ) (hB : fairBitCount n ε δ≤B) (bits : BitWord B) : ℚ := flatFPRASOutput n r O ε δ (bitPrefix _ B hB bits) lemma paddedFPRASOutput_law (n r : ℕ) (O : IndependenceOracle n) (ε δ : ℚ) (B : ℕ) (hB : fairBitCount n ε δ≤B) (φ : ℚ → ℝ) : uniformAverage (fun bits => φ (paddedFPRASOutput n r O ε δ B hB bits))= uniformAverage (fun bits => φ (canonicalBoundedOutput n r O ε δ bits)) := by unfold paddedFPRASOutput rw [uniformAverage_bitPrefix _ B hB (fun w => φ (flatFPRASOutput n r O ε δ w))] unfold flatFPRASOutput exact uniformAverage_equiv (bankWordEquiv n ε δ) (fun w : FPRASBank n ε δ => φ (canonicalBoundedOutput n r O ε δ w)) lemma uniformAverage_indicator_card {X : Type*} [Fintype X] (P : X → Prop) : uniformAverage (fun x => if P x then (1:ℝ) else 0)= (Nat.card {x // P x}:ℝ)/(Fintype.card X:ℝ) := by simp [uniformAverage,Nat.card_eq_fintype_card,Fintype.card_subtype] theorem padded_fair_experiment (n r : ℕ) (O : IndependenceOracle n) (M₁ M₂ : Matroid (Fin n)) (hO : ExactOracles M₁ M₂ O) (hE₁ : M₁.E=Set.univ) (hE₂ : M₂.E=Set.univ) (hr₁ : M₁.eRank=(r:ℕ∞)) (hr₂ : M₂.eRank=(r:ℕ∞)) (ε δ : ℚ) (hε0 : 0<ε) (hε1 : ε<1) (hδ : 0<δ) (B : ℕ) (hB : fairBitCount n ε δ≤B) : (∀ bits : BitWord B,0≤paddedFPRASOutput n r O ε δ B hB bits ∧ (commonBaseCount M₁ M₂=0 → paddedFPRASOutput n r O ε δ B hB bits=0)) ∧ (1-δ)*(2:ℚ)^B≤(Nat.card {bits : BitWord B // relativeAccuracy ε (commonBaseCount M₁ M₂) (paddedFPRASOutput n r O ε δ B hB bits)}:ℚ) := by have hfull := canonical_bounded_fair_experiment n r O M₁ M₂ hO hE₁ hE₂ hr₁ hr₂ ε δ hε0 hε1 hδ constructor · intro bits exact hfull.1 _ · have h := hfull.2 rw [←paddedFPRASOutput_law n r O ε δ B hB (fun z => if relativeAccuracy ε (commonBaseCount M₁ M₂) z then (1:ℝ) else 0)] at h rw [uniformAverage_indicator_card] at h have hcard : Fintype.card (BitWord B)=2^B := by simp [BitWord] rw [hcard,Nat.cast_pow,Nat.cast_ofNat] at h have hh := (le_div_iff₀ (by positivity : (0:ℝ)<2^B)).mp h exact_mod_cast hh section inductive OracleDraw (n : ℕ) (A : Type) where | pure : A → OracleDraw n A | query : Bool → (Fin n → Bool) → (Bool → OracleDraw n A) → OracleDraw n A | draw : (v : ℕ) → (Fin (v+1) → OracleDraw n A) → OracleDraw n A namespace OracleDraw variable {n : ℕ} {A B : Type} def bind : OracleDraw n A → (A → OracleDraw n B) → OracleDraw n B | .pure a,f => f a | .query w S k,f => .query w S (fun b => (k b).bind f) | .draw v k,f => .draw v (fun i => (k i).bind f) def map (t : OracleDraw n A) (f : A → B) : OracleDraw n B := t.bind (fun a => .pure (f a)) def lift : DrawTree A → OracleDraw n A | .leaf a => .pure a | .draw v k => .draw v (fun i => lift (k i)) def resolve (O : IndependenceOracle n) : OracleDraw n A → DrawTree A | .pure a => .leaf a | .query w S k => resolve O (k (O w S)) | .draw v k => .draw v (fun i => resolve O (k i)) lemma resolve_bind (O : IndependenceOracle n) (t : OracleDraw n A) (f : A → OracleDraw n B) : resolve O (t.bind f)=(resolve O t).bind (fun a => resolve O (f a)) := by induction t with | pure a => rfl | query w S k ih => exact ih (O w S) | draw v k ih => simp only [bind,resolve,DrawTree.bind]; congr; funext i; exact ih i lemma resolve_map (O : IndependenceOracle n) (t : OracleDraw n A) (f : A → B) : resolve O (t.map f)=(resolve O t).map f := resolve_bind O t _ lemma resolve_lift (O : IndependenceOracle n) (t : DrawTree A) : resolve O (lift t)=t := by induction t with | leaf a => rfl | draw v k ih => simp only [lift,resolve]; congr; funext i; exact ih i def Queries : ℕ → OracleDraw n A → Prop | _,.pure _ => True | Q,.query _ _ k => 0 ∀ i,Queries Q (k i) lemma queries_mono (t : OracleDraw n A) {Q R : ℕ} (h : Queries Q t) (hle : Q≤R) : Queries R t := by induction t generalizing Q R with | pure a => trivial | query w S k ih => have hq := h.1 exact ⟨by omega,fun b => ih b (h.2 b) (by omega)⟩ | draw v k ih => exact fun i => ih i (h i) hle lemma queries_bind (t : OracleDraw n A) (f : A → OracleDraw n B) (Q R : ℕ) (ht : Queries Q t) (hf : ∀ a,Queries R (f a)) : Queries (Q+R) (t.bind f) := by induction t generalizing Q with | pure a => exact queries_mono (f a) (hf a) (by omega) | query w S k ih => have hq := ht.1 refine ⟨by omega,?_⟩ intro b have he : Q+R-1=(Q-1)+R := by have hq := ht.1; omega rw [he]; exact ih b (Q-1) (ht.2 b) | draw v k ih => exact fun i => ih i Q (ht i) lemma queries_map (t : OracleDraw n A) (f : A → B) (Q : ℕ) (ht : Queries Q t) : Queries Q (t.map f) := by exact queries_bind t (fun a => .pure (f a)) Q 0 ht (fun _ => trivial) lemma queries_lift (t : DrawTree A) : Queries 0 (lift t : OracleDraw n A) := by induction t with | leaf a => trivial | draw v k ih => exact ih def run (O : IndependenceOracle n) (H D : ℕ) : OracleDraw n A → (M : ℕ) → (Fin M → Fin D → BitWord H) → Option A × ℕ | .pure a,_,_ => (some a,0) | .query w S k,M,bits => let out := run O H D (k (O w S)) M bits (out.1,out.2+1) | .draw _ _,0,_ => (none,0) | .draw v k,M+1,bits => if hh : Nat.clog 2 (v+1)≤H then match boundedUniform (v+1) (Nat.clog 2 (v+1)) D (fun d => bitPrefix _ H hh (bits 0 d)) with | none => (none,0) | some i => run O H D (k i) M (Fin.tail bits) else (none,0) lemma run_resolve (O : IndependenceOracle n) (H D : ℕ) (t : OracleDraw n A) (M : ℕ) (bits : Fin M → Fin D → BitWord H) : (run O H D t M bits).1=DrawTree.run H D M (resolve O t) bits := by induction t generalizing M with | pure a => simp [run,resolve,DrawTree.run] | query w S k ih => exact ih (O w S) M bits | draw v k ih => cases M with | zero => rfl | succ M => simp only [run,resolve,DrawTree.run] split_ifs · split <;> rename_i he · simp only [] · simpa only [he] using ih _ M (Fin.tail bits) · rfl lemma run_queries (O : IndependenceOracle n) (H D : ℕ) (t : OracleDraw n A) (Q M : ℕ) (ht : Queries Q t) (bits : Fin M → Fin D → BitWord H) : (run O H D t M bits).2≤Q := by induction t generalizing Q M with | pure a => simp [run] | query w S k ih => have hq := ht.1 have h := ih (O w S) (Q-1) M (ht.2 _) bits change (run O H D (k (O w S)) M bits).2+1≤Q omega | draw v k ih => cases M with | zero => simp [run] | succ M => simp only [run] split_ifs · split · simp · exact ih _ Q M (ht _) _ · simp end OracleDraw open scoped Classical variable {n : ℕ} def greedyEffect (which : Bool) : List (Fin n) → OracleDraw n (Finset (Fin n)) | [] => .pure ∅ | a::l => (greedyEffect which l).bind (fun I => .query which (fun i => decide (i ∈ insert a I)) (fun b => .pure (if b then insert a I else I))) lemma greedyEffect_resolve (O : IndependenceOracle n) (which : Bool) (l : List (Fin n)) : OracleDraw.resolve O (greedyEffect which l)=.leaf (greedyOracle (queryFinset O which) l) := by induction l with | nil => rfl | cons a l ih => simp [greedyEffect,OracleDraw.resolve_bind,ih,DrawTree.bind,OracleDraw.resolve,greedyOracle,queryFinset] lemma greedyEffect_queries (which : Bool) (l : List (Fin n)) : OracleDraw.Queries l.length (greedyEffect which l) := by induction l with | nil => trivial | cons a l ih => exact OracleDraw.queries_bind _ _ l.length 1 ih (fun I => ⟨by omega,fun b => trivial⟩) def rankEffect (which : Bool) (S : Finset (Fin n)) : OracleDraw n ℕ := (greedyEffect which ((List.finRange n).filter (fun i => decide (i ∈ S)))).map Finset.card lemma rankEffect_resolve (O : IndependenceOracle n) (which : Bool) (S : Finset (Fin n)) : OracleDraw.resolve O (rankEffect which S)=.leaf (rankOracle O which S) := by simp [rankEffect,OracleDraw.resolve_map,greedyEffect_resolve,DrawTree.map,DrawTree.bind,rankOracle] lemma rankEffect_queries (which : Bool) (S : Finset (Fin n)) : OracleDraw.Queries n (rankEffect which S) := by apply OracleDraw.queries_mono _ (OracleDraw.queries_map _ _ _ (greedyEffect_queries which _)) exact (List.length_filter_le _ _).trans_eq (List.length_finRange (n := n)) noncomputable def deficiencyEffect (r : ℕ) (S : Set (Fin n ⊕ Fin n)) : OracleDraw n ℕ := (rankEffect false (Sum.inl ⁻¹' S).toFinset).bind (fun rx => (rankEffect true (Sum.inr ⁻¹' S).toFinsetᶜ).map (fun rc => n+r-(rx+(Sum.inr ⁻¹' S).toFinset.card+rc))) lemma deficiencyEffect_resolve (O : IndependenceOracle n) (r : ℕ) (S : Set (Fin n ⊕ Fin n)) : OracleDraw.resolve O (deficiencyEffect r S)=.leaf (oracleDeficiency n r O S) := by simp [deficiencyEffect,OracleDraw.resolve_bind,OracleDraw.resolve_map,rankEffect_resolve, DrawTree.map,DrawTree.bind,oracleDeficiency,pairedDeficiencyOracle] lemma deficiencyEffect_queries (r : ℕ) (S : Set (Fin n ⊕ Fin n)) : OracleDraw.Queries (2*n) (deficiencyEffect r S) := by simpa only [two_mul,deficiencyEffect] using OracleDraw.queries_bind _ _ n n (rankEffect_queries false _) (fun rx => OracleDraw.queries_map _ _ n (rankEffect_queries true _)) end section namespace OracleDraw open scoped Classical variable {n : ℕ} {A B : Type} def optionBind (t : OracleDraw n (Option A)) (f : A → OracleDraw n (Option B)) : OracleDraw n (Option B) := t.bind (fun a => match a with | none => .pure none | some a => f a) lemma resolve_optionBind (O : IndependenceOracle n) (t : OracleDraw n (Option A)) (f : A → OracleDraw n (Option B)) : resolve O (t.optionBind f)=(resolve O t).optionBind (fun a => resolve O (f a)) := by rw [optionBind,resolve_bind,DrawTree.optionBind]; congr; funext a; cases a <;> rfl lemma queries_optionBind (t : OracleDraw n (Option A)) (f : A → OracleDraw n (Option B)) (Q R : ℕ) (ht : Queries Q t) (hf : ∀ a,Queries R (f a)) : Queries (Q+R) (t.optionBind f) := by apply queries_bind _ _ Q R ht intro a; cases a with | none => trivial | some a => exact hf a def iterate (t : A → OracleDraw n (Option A)) : ℕ → A → OracleDraw n (Option A) | 0,a => .pure (some a) | k+1,a => (iterate t k a).optionBind t lemma resolve_iterate (O : IndependenceOracle n) (t : A → OracleDraw n (Option A)) (k : ℕ) (a : A) : resolve O (iterate t k a)=DrawTree.iterate (fun a => resolve O (t a)) k a := by induction k with | zero => rfl | succ k ih => simp [iterate,resolve_optionBind,ih,DrawTree.iterate] lemma queries_iterate (t : A → OracleDraw n (Option A)) (Q k : ℕ) (ht : ∀ a,Queries Q (t a)) (a : A) : Queries (Q*k) (iterate t k a) := by induction k with | zero => trivial | succ k ih => simpa only [iterate,Nat.mul_succ] using queries_optionBind _ t (Q*k) Q ih ht def sample (step : A → OracleDraw n A) : (k : ℕ) → A → OracleDraw n (FiniteChain.Sample A k) | 0,a => .pure a | k+1,a => (step a).bind (fun b => (sample step k b).map (fun v => (a,v))) lemma resolve_sample (O : IndependenceOracle n) (step : A → OracleDraw n A) (k : ℕ) (a : A) : resolve O (sample step k a)=DrawTree.sample (fun a => resolve O (step a)) k a := by induction k generalizing a with | zero => rfl | succ k ih => simp only [sample,resolve_bind,DrawTree.sample] congr; funext b exact (resolve_map O (sample step k b) (fun v => (a,v))).trans (by rw [ih]; rfl) lemma queries_sample (step : A → OracleDraw n A) (Q k : ℕ) (hs : ∀ a,Queries Q (step a)) (a : A) : Queries (Q*k) (sample step k a) := by induction k generalizing a with | zero => trivial | succ k ih => simpa only [sample,Nat.mul_succ,Nat.add_comm] using queries_bind (step a) _ Q (Q*k) (hs a) (fun b => queries_map _ _ _ (ih b)) noncomputable def hitting (step : A → OracleDraw n A) (p : A → Prop) : ℕ → A → OracleDraw n (Option {a // p a}) | 0,_ => .pure none | k+1,a => (step a).bind (fun b => if hb : p b then .pure (some ⟨b,hb⟩) else hitting step p k b) lemma resolve_hitting [Fintype A] (O : IndependenceOracle n) (step : A → OracleDraw n A) (p : A → Prop) (k : ℕ) (a : A) : resolve O (hitting step p k a)=hittingTree (fun a => resolve O (step a)) p k a := by induction k generalizing a with | zero => rfl | succ k ih => simp only [hitting,resolve_bind,hittingTree] congr; funext b; split_ifs <;> first | rfl | exact ih b lemma queries_hitting (step : A → OracleDraw n A) (p : A → Prop) (Q k : ℕ) (hs : ∀ a,Queries Q (step a)) (a : A) : Queries (Q*k) (hitting step p k a) := by induction k generalizing a with | zero => trivial | succ k ih => have h := queries_bind (step a) (fun b => if hb : p b then .pure (some ⟨b,hb⟩) else hitting step p k b) Q (Q*k) (hs a) (by intro b; split_ifs; exacts [trivial,ih b]) simpa only [hitting,Nat.mul_succ,Nat.add_comm] using h noncomputable def traverse (f : A → OracleDraw n B) : List A → OracleDraw n (List B) | [] => .pure [] | a::l => (f a).bind (fun b => (traverse f l).map (fun xs => b::xs)) lemma traverse_resolve (O : IndependenceOracle n) (f : A → OracleDraw n B) (g : A → B) (hf : ∀ a,resolve O (f a)=.leaf (g a)) (l : List A) : resolve O (traverse f l)=.leaf (l.map g) := by induction l with | nil => rfl | cons a l ih => simp [traverse,resolve_bind,resolve_map,hf,ih,DrawTree.bind,DrawTree.map] lemma traverse_queries (f : A → OracleDraw n B) (Q : ℕ) (hf : ∀ a,Queries Q (f a)) (l : List A) : Queries (Q*l.length) (traverse f l) := by induction l with | nil => trivial | cons a l ih => simpa only [traverse,List.length_cons,Nat.mul_succ,Nat.add_comm] using queries_bind (f a) _ Q (Q*l.length) (hf a) (fun b => queries_map _ _ _ ih) end OracleDraw open scoped BigOperators Classical variable (n : ℕ) (hn : 0 pairedSlots n noncomputable def exchangeEffect (w : ((Fin n ⊕ Fin n) × (Fin n ⊕ Fin n)) → ((Fin n ⊕ Fin n) × (Fin n ⊕ Fin n)) → ℚ) (j : ℕ) (S : ChainIndex GS) (a : ExchangeChoice S.val) : OracleDraw n (ChainIndex GS) := if ht : ChainState GS (exchangedSet S.val a) then let T : ChainIndex GS := ⟨exchangedSet S.val a,ht⟩ (deficiencyEffect r S.val).bind (fun ds => (deficiencyEffect r T.val).bind (fun dt => OracleDraw.lift ((DrawTree.bernoulli (min 1 ((rationalMultiplier GS w T.val*(rationalRho n^j)^dt)/ (rationalMultiplier GS w S.val*(rationalRho n^j)^ds)))).map (fun accept => if accept then T else S)))) else .pure S lemma exchangeEffect_resolve (O : IndependenceOracle n) (w) (j : ℕ) (S : ChainIndex GS) (a : ExchangeChoice S.val) : OracleDraw.resolve O (exchangeEffect n r w j S a)=rationalExchange GS w (oracleAnneal n r O j) S a := by unfold exchangeEffect rationalExchange split_ifs · simp only [OracleDraw.resolve_bind,deficiencyEffect_resolve,DrawTree.bind,OracleDraw.resolve_lift] rfl · rfl lemma exchangeEffect_queries (w) (j : ℕ) (S : ChainIndex GS) (a : ExchangeChoice S.val) : OracleDraw.Queries (4*n) (exchangeEffect n r w j S a) := by unfold exchangeEffect split_ifs · rw [show 4*n=2*n+2*n by omega] apply OracleDraw.queries_bind _ _ (2*n) (2*n) (deficiencyEffect_queries r _) intro ds exact OracleDraw.queries_bind _ _ (2*n) 0 (deficiencyEffect_queries r _) (fun dt => OracleDraw.queries_lift _) · trivial noncomputable def stepEffect (h : List (PhaseSample n N)) (j : ℕ) (S : ChainIndex GS) : OracleDraw n (ChainIndex GS) := letI : Nonempty (ExchangeChoice S.val) := Fintype.card_pos_iff.mp (by rw [exchangeChoice_card GS (pairedSlots_fresh n) (pairedSlots_cover n),pairedSlots_length]; positivity) (OracleDraw.lift (DrawTree.bernoulli (1/2))).bind (fun lazy => if lazy then .pure S else (OracleDraw.lift (DrawTree.uniformVia (ExchangeChoice S.val) (canonicalExchangeEnumeration n S.val))).bind (exchangeEffect n r (rationalStored n N h j) j S)) lemma stepEffect_resolve (O : IndependenceOracle n) (h : List (PhaseSample n N)) (j : ℕ) (S : ChainIndex GS) : OracleDraw.resolve O (stepEffect n hn r N h j S)=canonicalStepTree n hn r O N h j S := by unfold stepEffect canonicalStepTree canonicalMetropolis simp only [OracleDraw.resolve_bind,OracleDraw.resolve_lift] congr; funext a; cases a · simp only [Bool.false_eq_true,ite_false,OracleDraw.resolve_bind,OracleDraw.resolve_lift] congr; funext b; exact exchangeEffect_resolve n r O _ _ _ _ · rfl lemma stepEffect_queries (h : List (PhaseSample n N)) (j : ℕ) (S : ChainIndex GS) : OracleDraw.Queries (4*n) (stepEffect n hn r N h j S) := by let : Nonempty (ExchangeChoice S.val) := Fintype.card_pos_iff.mp (by rw [exchangeChoice_card GS (pairedSlots_fresh n) (pairedSlots_cover n),pairedSlots_length]; positivity) have hp : OracleDraw.Queries (0+4*n) (stepEffect n hn r N h j S) := by unfold stepEffect apply OracleDraw.queries_bind _ _ 0 (4*n) (OracleDraw.queries_lift _) intro a; cases a · simp only [Bool.false_eq_true,ite_false] have hq : OracleDraw.Queries (0+4*n) ((OracleDraw.lift (DrawTree.uniformVia (ExchangeChoice S.val) (canonicalExchangeEnumeration n S.val))).bind (exchangeEffect n r (rationalStored n N h j) j S)) := OracleDraw.queries_bind _ _ 0 (4*n) (OracleDraw.queries_lift _) (fun b => exchangeEffect_queries n r _ _ _ b) simpa only [Nat.zero_add] using hq · trivial simpa only [Nat.zero_add] using hp noncomputable def traceEffect (h : List (PhaseSample n N)) (j cap : ℕ) (x : PlainIndex GS) : OracleDraw n (Option (PlainIndex GS)) := OracleDraw.hitting (stepEffect n hn r N h j) (plainPredicate GS) (cap+1) x.val lemma traceEffect_resolve (O : IndependenceOracle n) (h : List (PhaseSample n N)) (j cap : ℕ) (x : PlainIndex GS) : OracleDraw.resolve O (traceEffect n hn r N h j cap x)=canonicalTraceTree n hn r O N h j cap x := by simp only [traceEffect,OracleDraw.resolve_hitting,stepEffect_resolve,canonicalTraceTree] lemma traceEffect_queries (h : List (PhaseSample n N)) (j cap : ℕ) (x : PlainIndex GS) : OracleDraw.Queries (4*n*(cap+1)) (traceEffect n hn r N h j cap x) := OracleDraw.queries_hitting _ _ _ _ (stepEffect_queries n hn r N h j) _ noncomputable def restartEffect (h : List (PhaseSample n N)) (cap : ℕ) : ℕ → OracleDraw n (Option (PlainIndex GS)) | 0 => letI := plainIndex_nonempty GS (pairedSlots_fresh n) (pairedSlots_cover n) OracleDraw.lift ((DrawTree.uniformVia (PlainIndex GS) (canonicalPlainEnumeration n)).map some) | j+1 => (restartEffect h cap j).optionBind (OracleDraw.iterate (traceEffect n hn r N h (j+1) cap) (20*n^4*(n*(L+1)+2))) lemma restartEffect_resolve (O : IndependenceOracle n) (h : List (PhaseSample n N)) (cap j : ℕ) : OracleDraw.resolve O (restartEffect n hn r N L h cap j)=canonicalRestartTree n hn r O N L h cap j := by induction j with | zero => exact OracleDraw.resolve_lift O _ | succ j ih => simp only [restartEffect,canonicalRestartTree,OracleDraw.resolve_optionBind, OracleDraw.resolve_iterate,traceEffect_resolve,ih] lemma restartEffect_queries (h : List (PhaseSample n N)) (cap j : ℕ) : OracleDraw.Queries (4*n*(cap+1)*(20*n^4*(n*(L+1)+2))*j) (restartEffect n hn r N L h cap j) := by induction j with | zero => exact OracleDraw.queries_lift _ | succ j ih => simpa only [restartEffect,Nat.mul_succ] using OracleDraw.queries_optionBind _ _ _ _ ih (OracleDraw.queries_iterate _ _ _ (traceEffect_queries n hn r N h (j+1) cap)) noncomputable def startEffect (h : List (PhaseSample n N)) : OracleDraw n (Option (ChainIndex GS)) := (restartEffect n hn r N L h (restartCap n L) h.length).map (Option.map Subtype.val) noncomputable def phaseEffect (h : List (PhaseSample n N)) : OracleDraw n (Option (PhaseSample n N)) := if rationalHistoryPositive n N h then (startEffect n hn r N L h).optionBind (fun x => (OracleDraw.sample (stepEffect n hn r N h h.length) (N-1) x).map some) else .pure none lemma phaseEffect_resolve (O : IndependenceOracle n) (h : List (PhaseSample n N)) : OracleDraw.resolve O (phaseEffect n hn r N L h)=canonicalPhaseTree n hn r O N L h := by unfold phaseEffect canonicalPhaseTree split_ifs · simp only [OracleDraw.resolve_optionBind,startEffect,OracleDraw.resolve_map,restartEffect_resolve, canonicalStartTree,OracleDraw.resolve_sample,stepEffect_resolve] · rfl noncomputable def witnessEffect (h : List (PhaseSample n N)) : OracleDraw n (Option (PlainIndex GS)) := if rationalHistoryPositive n N h then restartEffect n hn r N L h (restartCap n L) h.length else .pure none lemma witnessEffect_resolve (O : IndependenceOracle n) (h : List (PhaseSample n N)) : OracleDraw.resolve O (witnessEffect n hn r N L h)=canonicalWitnessTree n hn r O N L h := by unfold witnessEffect canonicalWitnessTree split_ifs · exact restartEffect_resolve n hn r N L O h _ _ · rfl end section open scoped BigOperators Classical variable (n : ℕ) (hn : 0 pairedSlots n noncomputable def ratioEffect (l : List (Set (Fin n ⊕ Fin n))) : OracleDraw n ℚ := (OracleDraw.traverse (fun S => (deficiencyEffect r S).map (fun d => rationalPlain GS (fun _ => rationalRho n ^ d) S)) l).map (fun vs => (vs.sum/(l.length:ℚ))/rationalEmpirical (rationalPlain GS (fun _ => 1)) l) lemma ratioEffect_resolve (O : IndependenceOracle n) (l : List (Set (Fin n ⊕ Fin n))) : OracleDraw.resolve O (ratioEffect n r l)=.leaf (rationalRatio GS (fun S => rationalRho n ^ oracleDeficiency n r O S) l) := by unfold ratioEffect rw [OracleDraw.resolve_map,OracleDraw.traverse_resolve O _ (fun S => rationalPlain GS (fun _ => rationalRho n ^ oracleDeficiency n r O S) S)] · simp only [DrawTree.map,DrawTree.bind,rationalRatio,rationalEmpirical] congr 3 · intro S; simp only [OracleDraw.resolve_map,deficiencyEffect_resolve,DrawTree.map,DrawTree.bind] lemma ratioEffect_queries (l : List (Set (Fin n ⊕ Fin n))) : OracleDraw.Queries (2*n*l.length) (ratioEffect n r l) := by apply OracleDraw.queries_map exact OracleDraw.traverse_queries _ (2*n) (fun S => OracleDraw.queries_map _ _ _ (deficiencyEffect_queries r S)) l lemma historySample_length_bound (h : List (PhaseSample n N)) (j : ℕ) : (historySample (observedSets n N) h j).length≤N+1 := by unfold historySample by_cases hj : j .pure 1 | j+1 => (estimateProductEffect h j).bind (fun z => (ratioEffect n r (historySample (observedSets n N) h j)).map (fun q => z*q)) lemma estimateProductEffect_resolve (O : IndependenceOracle n) (h : List (PhaseSample n N)) (j : ℕ) : OracleDraw.resolve O (estimateProductEffect n r N h j)=.leaf (∏ i ∈ Finset.range j,rationalRatio GS (fun S => rationalRho n ^ oracleDeficiency n r O S) (historySample (observedSets n N) h i)) := by induction j with | zero => simp [estimateProductEffect,OracleDraw.resolve] | succ j ih => simp only [estimateProductEffect,OracleDraw.resolve_bind,ih,DrawTree.bind, OracleDraw.resolve_map,ratioEffect_resolve,DrawTree.map,Finset.prod_range_succ] lemma estimateProductEffect_queries (h : List (PhaseSample n N)) (j : ℕ) : OracleDraw.Queries (2*n*(N+1)*j) (estimateProductEffect n r N h j) := by induction j with | zero => trivial | succ j ih => rw [Nat.mul_succ] apply OracleDraw.queries_bind _ _ _ _ ih intro z apply OracleDraw.queries_map exact OracleDraw.queries_mono _ (ratioEffect_queries n r _) (by have hh := historySample_length_bound n N h j gcongr) noncomputable def estimateEffect (h : List (PhaseSample n N)) : OracleDraw n ℚ := (estimateProductEffect n r N h L).map (fun z => (2:ℚ)^n*z) lemma estimateEffect_resolve (O : IndependenceOracle n) (h : List (PhaseSample n N)) : OracleDraw.resolve O (estimateEffect n r N L h)=.leaf (oracleEstimate n r O N L h) := by simp only [estimateEffect,OracleDraw.resolve_map,estimateProductEffect_resolve,DrawTree.map,DrawTree.bind,oracleEstimate] lemma estimateEffect_queries (h : List (PhaseSample n N)) : OracleDraw.Queries (2*n*(N+1)*L) (estimateEffect n r N L h) := OracleDraw.queries_map _ _ _ (estimateProductEffect_queries n r N h L) noncomputable def guardEffect (h : List (PhaseSample n N)) (x : PlainIndex GS) : OracleDraw n ℚ := (deficiencyEffect r x.val.val).bind (fun d => if d=0 then estimateEffect n r N L h else .pure 0) lemma guardEffect_resolve (O : IndependenceOracle n) (h : List (PhaseSample n N)) (x : PlainIndex GS) : OracleDraw.resolve O (guardEffect n r N L h x)=.leaf (oracleGuard n r O N L h x) := by simp only [guardEffect,OracleDraw.resolve_bind,deficiencyEffect_resolve,DrawTree.bind,oracleGuard] split_ifs · exact estimateEffect_resolve n r N L O h · rfl lemma guardEffect_queries (h : List (PhaseSample n N)) (x : PlainIndex GS) : OracleDraw.Queries (2*n+2*n*(N+1)*L) (guardEffect n r N L h x) := by apply OracleDraw.queries_bind _ _ _ _ (deficiencyEffect_queries r _) intro d; split_ifs · exact estimateEffect_queries n r N L h · trivial noncomputable def finishEffect (h : List (PhaseSample n N)) : OracleDraw n (Option ℚ) := (witnessEffect n hn r N L h).optionBind (fun x => (guardEffect n r N L h x).map some) lemma finishEffect_resolve (O : IndependenceOracle n) (h : List (PhaseSample n N)) : OracleDraw.resolve O (finishEffect n hn r N L h)= (canonicalWitnessTree n hn r O N L h).map (Option.map (oracleGuard n r O N L h)) := by rw [finishEffect,OracleDraw.resolve_optionBind,witnessEffect_resolve] simp only [OracleDraw.resolve_map,guardEffect_resolve,DrawTree.map,DrawTree.bind,DrawTree.optionBind] congr; funext a; cases a <;> rfl noncomputable def historyFinishEffect : List (PhaseSample n N) → ℕ → OracleDraw n (Option ℚ) | h,0 => finishEffect n hn r N L h | h,k+1 => (phaseEffect n hn r N L h).optionBind (fun x => historyFinishEffect (h++[x]) k) lemma historyFinishEffect_resolve (O : IndependenceOracle n) (h : List (PhaseSample n N)) (k : ℕ) : OracleDraw.resolve O (historyFinishEffect n hn r N L h k)= (DrawTree.history (canonicalPhaseTree n hn r O N L) k h).optionBind (fun h => (canonicalWitnessTree n hn r O N L h).map (Option.map (oracleGuard n r O N L h))) := by induction k generalizing h with | zero => exact finishEffect_resolve n hn r N L O h | succ k ih => simp only [historyFinishEffect,OracleDraw.resolve_optionBind,phaseEffect_resolve,ih, DrawTree.history,DrawTree.optionBind_assoc] noncomputable def queryAlgorithm : OracleDraw n (Option ℚ) := historyFinishEffect n hn r N L [] L lemma queryAlgorithm_resolve (O : IndependenceOracle n) : OracleDraw.resolve O (queryAlgorithm n hn r N L)=canonicalAlgorithmTree n hn r O N L := historyFinishEffect_resolve n hn r N L O [] L end section open scoped Classical variable (n : ℕ) (hn : 0 OracleDraw.queries_map _ _ _ (guardEffect_queries n r N L h x)) apply OracleDraw.queries_mono _ hp unfold phaseQueryBound have h1 : 4*n*(restartCap n L+1)*(20*n^4*(n*(L+1)+2))*h.length≤ 4*n*(restartCap n L+1)*(20*n^4*(n*(L+1)+2))*L := by gcongr omega lemma historyFinishEffect_queries (h : List (PhaseSample n N)) (k : ℕ) (hk : h.length+k≤L) : OracleDraw.Queries (phaseQueryBound n N L*(k+1)) (historyFinishEffect n hn r N L h k) := by induction k generalizing h with | zero => simpa only [historyFinishEffect,Nat.zero_add,Nat.mul_one] using finishEffect_queries n hn r N L h (by omega) | succ k ih => rw [show phaseQueryBound n N L*(k+1+1)=phaseQueryBound n N L+phaseQueryBound n N L*(k+1) by ring] apply OracleDraw.queries_optionBind _ _ _ _ (phaseEffect_queries n hn r N L h (by omega)) intro x; apply ih simp only [List.length_append,List.length_singleton]; omega def oracleQueryBound (n N L : ℕ) : ℕ := phaseQueryBound n N L*(L+1) lemma queryAlgorithm_queries : OracleDraw.Queries (oracleQueryBound n N L) (queryAlgorithm n hn r N L) := historyFinishEffect_queries n hn r N L [] L (by simp) lemma capped_queryAlgorithm (O : IndependenceOracle n) (H D M : ℕ) (bits : Fin M → Fin D → BitWord H) : (OracleDraw.run O H D (queryAlgorithm n hn r N L) M bits).1= DrawTree.run H D M (canonicalAlgorithmTree n hn r O N L) bits ∧ (OracleDraw.run O H D (queryAlgorithm n hn r N L) M bits).2≤oracleQueryBound n N L := by exact ⟨by rw [OracleDraw.run_resolve,queryAlgorithm_resolve], OracleDraw.run_queries O H D _ _ M (queryAlgorithm_queries n hn r N L) bits⟩ lemma oracleQueryBound_le (n N L : ℕ) : oracleQueryBound n N L≤4*n*(algorithmDrawBound n N L)+(2*n+2*n*(N+1)*L)*(L+1) := by have hp : 4*n*(restartCap n L+1)*(20*n^4*(n*(L+1)+2))*L+4*n*N≤4*n*phaseDrawBound n N L := by calc _ = 4*n*(L*(restartCap n L+1)*(20*n^4*(n*(L+1)+2))+N) := by ring _ ≤ 4*n*(1+3*(L*(restartCap n L+1)*(20*n^4*(n*(L+1)+2)))+3*N) := by gcongr <;> omega _ = _ := by unfold phaseDrawBound; ring calc _ ≤ (4*n*phaseDrawBound n N L+(2*n+2*n*(N+1)*L))*(L+1) := by unfold oracleQueryBound phaseQueryBound apply Nat.mul_le_mul_right omega _ = _ := by unfold algorithmDrawBound; ring theorem allQueries_polynomial (n : ℕ) (ε δ : ℚ) : repetitionCount δ*oracleQueryBound n (sampleCount n (annealLength n (accuracyExponent ε)) ε) (annealLength n (accuracyExponent ε))≤10^31*(bitResourceParameter n ε δ)^30 := by let T := bitResourceParameter n ε δ have hT : 0 queryFairOutput n hn r O N L (bits i) (rationalMedian (List.ofFn (fun i => (outs i).1)),∑ i,(outs i).2) lemma queryAmplifiedOutput_value (n : ℕ) (hn : 0 queryFairOutput_queries n hn r O N L (bits i))) simp noncomputable def queryBoundedOutput (n r : ℕ) (O : IndependenceOracle n) (ε δ : ℚ) (bits : FPRASBank n ε δ) : ℚ × ℕ := if hn : 0 bits (t+i)) u := by induction u with | zero => rfl | succ u ih => change machineStep P O (bits (t+u)) (execution P O c bits (t+u))= machineStep P O (bits (t+u)) (execution P O (execution P O c bits t) (fun i => bits (t+i)) u) rw [ih] def incrementProgram (a b : Fin (k+8)) : Program k 5 := fun pc => match pc.val with | 0 => .pop a 1 1 2 | 1 => .push a true 3 | 2 => .push b false 0 | 3 => .pop b 5 4 4 | 4 => .push a false 3 | _ => .halt def leadingOnes : List Bool → ℕ | [] => 0 | false::_ => 0 | true::xs => leadingOnes xs+1 def carryTail : List Bool → List Bool | [] => [true] | false::xs => true::xs | true::xs => carryTail xs lemma leadingOnes_le (xs : List Bool) : leadingOnes xs≤xs.length := by induction xs with | nil => simp [leadingOnes] | cons b xs ih => cases b <;> simp [leadingOnes,List.length_cons] ; omega lemma replicate_append_false (m : ℕ) (xs : List Bool) : List.replicate m false ++ false::xs=List.replicate (m+1) false++xs := by rw [List.replicate_succ']; simp lemma increment_carry (a b : Fin (k+8)) (hab : a≠b) (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) (xs ys : List Bool) (q c : ℕ) (bits : ℕ → Bool) : execution (incrementProgram a b) O (workConfig (pairRegisters R a b xs ys) 0 q c) bits (2*leadingOnes xs+2)= workConfig (pairRegisters R a b (carryTail xs) (List.replicate (leadingOnes xs) false++ys)) 3 q (c+2*leadingOnes xs+2) := by induction xs generalizing ys c bits with | nil => simp [leadingOnes,carryTail,execution,machineStep,incrementProgram,workConfig, pairRegisters_a _ _ _ hab,pairRegisters_update_a _ _ _ hab] | cons x xs ih => cases x with | false => simp [leadingOnes,carryTail,execution,machineStep,incrementProgram,workConfig, pairRegisters_a _ _ _ hab,pairRegisters_update_a _ _ _ hab] | true => have ht : execution (incrementProgram a b) O (workConfig (pairRegisters R a b (true::xs) ys) 0 q c) bits 2 = workConfig (pairRegisters R a b xs (false::ys)) 0 q (c+2) := by simp [execution,machineStep,incrementProgram,workConfig, pairRegisters_a _ _ _ hab,pairRegisters_b,pairRegisters_update_a _ _ _ hab,pairRegisters_update_b] rw [leadingOnes,show 2*(leadingOnes xs+1)+2=2+(2*leadingOnes xs+2) by omega,execution_add,ht,ih] simp only [carryTail,replicate_append_false] congr 1 ; omega lemma increment_restore (a b : Fin (k+8)) (hab : a≠b) (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) (m : ℕ) (xs : List Bool) (q c : ℕ) (bits : ℕ → Bool) : execution (incrementProgram a b) O (workConfig (pairRegisters R a b xs (List.replicate m false)) 3 q c) bits (2*m+1)=workConfig (pairRegisters R a b (List.replicate m false++xs) []) 5 q (c+2*m+1) := by induction m generalizing xs c bits with | zero => simp [execution,machineStep,incrementProgram,workConfig,pairRegisters_b] | succ m ih => have ht : execution (incrementProgram a b) O (workConfig (pairRegisters R a b xs (List.replicate (m+1) false)) 3 q c) bits 2 = workConfig (pairRegisters R a b (false::xs) (List.replicate m false)) 3 q (c+2) := by simp [execution,machineStep,incrementProgram,workConfig,List.replicate_succ, pairRegisters_b,pairRegisters_a _ _ _ hab,pairRegisters_update_b,pairRegisters_update_a _ _ _ hab] rw [show 2*(m+1)+1=2+(2*m+1) by omega,execution_add,ht,ih,replicate_append_false] congr 1 ; omega def incrementBits (xs : List Bool) : List Bool := List.replicate (leadingOnes xs) false ++ carryTail xs lemma incrementBits_correct (xs : List Bool) : binaryValue (incrementBits xs)=binaryValue xs+1 := by induction xs with | nil => simp [incrementBits,leadingOnes,carryTail,binaryValue] | cons x xs ih => cases x with | false => simp [incrementBits,leadingOnes,carryTail,binaryValue,Nat.add_comm] | true => have he : incrementBits (true::xs)=false::incrementBits xs := by simp [incrementBits,leadingOnes,carryTail,List.replicate_succ] rw [he,binaryValue,binaryValue,ih] simp; omega theorem increment_block (a b : Fin (k+8)) (hab : a≠b) (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) (xs : List Bool) (q c : ℕ) (bits : ℕ → Bool) : execution (incrementProgram a b) O (workConfig (pairRegisters R a b xs []) 0 q c) bits (4*leadingOnes xs+3)= workConfig (pairRegisters R a b (incrementBits xs) []) 5 q (c+4*leadingOnes xs+3) ∧ 4*leadingOnes xs+3≤4*xs.length+3 ∧ binaryValue (incrementBits xs)=binaryValue xs+1 := by refine ⟨?_,by have h := leadingOnes_le xs; omega,incrementBits_correct xs⟩ rw [show 4*leadingOnes xs+3=(2*leadingOnes xs+2)+(2*leadingOnes xs+1) by omega,execution_add, increment_carry a b hab] simp only [List.append_nil] rw [increment_restore a b hab] simp only [incrementBits] congr 1 ; omega end section variable {k s t n : ℕ} def Instruction.relabel (e : Fin (s+1) → Fin (t+1)) : Instruction k s → Instruction k t | .push i b j => .push i b (e j) | .pop i x y z => .pop i (e x) (e y) (e z) | .coin x y => .coin (e x) (e y) | .query w i x y => .query w i (e x) (e y) | .halt => .halt def relabelConfig (e : Fin (s+1) → Fin (t+1)) (c : MachineConfig k s) : MachineConfig k t := ⟨c.registers,e c.control,c.output,c.oracleCalls,c.bitOperations⟩ lemma machineStep_relabel (P : Program k s) (Q : Program k t) (e : Fin (s+1) → Fin (t+1)) (O : IndependenceOracle n) (b : Bool) (c : MachineConfig k s) (h : Q (e c.control)=(P c.control).relabel e) : machineStep Q O b (relabelConfig e c)=relabelConfig e (machineStep P O b c) := by cases hc : c.output with | some z => simp [machineStep,relabelConfig,hc] | none => cases hp : P c.control with | push i b j => simp [machineStep,relabelConfig,hc,h,hp,Instruction.relabel] | pop i x y z => cases hl : c.registers i with | nil => simp [machineStep,relabelConfig,hc,h,hp,Instruction.relabel,hl] | cons a l => cases a <;> simp [machineStep,relabelConfig,hc,h,hp,Instruction.relabel,hl] | coin x y => cases b <;> simp [machineStep,relabelConfig,hc,h,hp,Instruction.relabel] | query w i x y => by_cases hl : (c.registers i).length=n · simp [machineStep,relabelConfig,hc,h,hp,Instruction.relabel,hl,apply_ite] · simp [machineStep,relabelConfig,hc,h,hp,Instruction.relabel,hl] | halt => simp [machineStep,relabelConfig,hc,h,hp,Instruction.relabel] lemma machineStep_none_pre (P : Program k s) (O : IndependenceOracle n) (b : Bool) (c : MachineConfig k s) (h : (machineStep P O b c).output=none) : c.output=none := by cases hc : c.output with | none => rfl | some z => simp [machineStep,hc] at h lemma machineStep_none_not_halt (P : Program k s) (O : IndependenceOracle n) (b : Bool) (c : MachineConfig k s) (h : (machineStep P O b c).output=none) : P c.control≠.halt := by have hc := machineStep_none_pre P O b c h intro hh simp [machineStep,hc,hh] at h lemma execution_relabel (P : Program k s) (Q : Program k t) (e : Fin (s+1) → Fin (t+1)) (h : ∀ i,Q (e i)=(P i).relabel e) (O : IndependenceOracle n) (c : MachineConfig k s) (bits : ℕ → Bool) (u : ℕ) : execution Q O (relabelConfig e c) bits u=relabelConfig e (execution P O c bits u) := by induction u with | zero => rfl | succ u ih => simp only [execution,ih] exact machineStep_relabel P Q e O _ _ (h _) lemma execution_relabel_before_halt (P : Program k s) (Q : Program k t) (e : Fin (s+1) → Fin (t+1)) (exit : Fin (s+1)) (hexit : P exit=.halt) (h : ∀ i,i≠exit → Q (e i)=(P i).relabel e) (O : IndependenceOracle n) (c : MachineConfig k s) (bits : ℕ → Bool) (u : ℕ) (hu : (execution P O c bits u).output=none) : execution Q O (relabelConfig e c) bits u=relabelConfig e (execution P O c bits u) := by induction u with | zero => rfl | succ u ih => have hn := machineStep_none_pre P O (bits u) (execution P O c bits u) hu have hh := machineStep_none_not_halt P O (bits u) (execution P O c bits u) hu have he : (execution P O c bits u).control≠exit := by intro he; rw [he,hexit] at hh; exact hh rfl simp only [execution,ih hn] exact machineStep_relabel P Q e O _ _ (h _ he) def firstLabel (s t : ℕ) (i : Fin (s+1)) : Fin (s+t+1) := ⟨i.val,by omega⟩ def secondLabel (s t : ℕ) (i : Fin (t+1)) : Fin (s+t+1) := ⟨s+i.val,by omega⟩ def lastLabel (s : ℕ) : Fin (s+1) := ⟨s,by omega⟩ def concatProgram (P : Program k s) (Q : Program k t) : Program k (s+t) := fun i => if hi : i.val bits (u+i)) v) := by rw [execution_add,concat_first_run P Q hexit O c bits u hu,link_exit _ hc, concat_second_run] end section variable {k n : ℕ} def tripleRegisters (R : Fin (k+8) → List Bool) (a b d : Fin (k+8)) (xs ys zs : List Bool) := Function.update (pairRegisters R a b xs ys) d zs lemma tripleRegisters_a (R : Fin (k+8) → List Bool) (a b d : Fin (k+8)) (hab : a≠b) (had : a≠d) (xs ys zs : List Bool) : tripleRegisters R a b d xs ys zs a=xs := by simp [tripleRegisters,pairRegisters,hab,had] lemma tripleRegisters_b (R : Fin (k+8) → List Bool) (a b d : Fin (k+8)) (hbd : b≠d) (xs ys zs : List Bool) : tripleRegisters R a b d xs ys zs b=ys := by simp [tripleRegisters,pairRegisters,hbd] lemma tripleRegisters_d (R : Fin (k+8) → List Bool) (a b d : Fin (k+8)) (xs ys zs : List Bool) : tripleRegisters R a b d xs ys zs d=zs := by simp [tripleRegisters] lemma tripleRegisters_update_a (R : Fin (k+8) → List Bool) (a b d : Fin (k+8)) (hab : a≠b) (had : a≠d) (xs ys zs ws : List Bool) : Function.update (tripleRegisters R a b d xs ys zs) a ws=tripleRegisters R a b d ws ys zs := by funext i by_cases ha : i=a · subst i; simp [tripleRegisters,pairRegisters,hab,had] · by_cases hb : i=b · subst i; by_cases hbd : b=d <;> simp [tripleRegisters,pairRegisters,ha,hbd,Ne.symm had] · by_cases hd : i=d · subst i; simp [tripleRegisters,pairRegisters,ha] · simp [tripleRegisters,pairRegisters,ha,hb,hd] lemma tripleRegisters_update_b (R : Fin (k+8) → List Bool) (a b d : Fin (k+8)) (hbd : b≠d) (xs ys zs ws : List Bool) : Function.update (tripleRegisters R a b d xs ys zs) b ws=tripleRegisters R a b d xs ws zs := by funext i by_cases hb : i=b · subst i; simp [tripleRegisters,pairRegisters,hbd] · by_cases hd : i=d · subst i; simp [tripleRegisters,pairRegisters,hb] · simp [tripleRegisters,pairRegisters,hb,hd] lemma tripleRegisters_update_d (R : Fin (k+8) → List Bool) (a b d : Fin (k+8)) (xs ys zs ws : List Bool) : Function.update (tripleRegisters R a b d xs ys zs) d ws=tripleRegisters R a b d xs ys ws := by simp [tripleRegisters] def copyConfig (R : Fin (k+8) → List Bool) (pc : Fin 9) (q c : ℕ) : MachineConfig k 8 := ⟨R,pc,none,q,c⟩ def copyProgram (a b d : Fin (k+8)) : Program k 8 := fun pc => match pc.val with | 0 => .pop a 3 1 2 | 1 => .push b false 0 | 2 => .push b true 0 | 3 => .pop b 8 4 5 | 4 => .push a false 6 | 5 => .push a true 7 | 6 => .push d false 3 | 7 => .push d true 3 | _ => .halt lemma copy_scan (a b d : Fin (k+8)) (hab : a≠b) (had : a≠d) (hbd : b≠d) (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) (xs ys zs : List Bool) (q c : ℕ) (bits : ℕ → Bool) : execution (copyProgram a b d) O (copyConfig (tripleRegisters R a b d xs ys zs) 0 q c) bits (2*xs.length+1)=copyConfig (tripleRegisters R a b d [] (xs.reverse++ys) zs) 3 q (c+2*xs.length+1) := by induction xs generalizing ys c bits with | nil => simp [execution,machineStep,copyProgram,copyConfig,tripleRegisters_a _ _ _ _ hab had] | cons x xs ih => have ht : execution (copyProgram a b d) O (copyConfig (tripleRegisters R a b d (x::xs) ys zs) 0 q c) bits 2= copyConfig (tripleRegisters R a b d xs (x::ys) zs) 0 q (c+2) := by cases x <;> simp [execution,machineStep,copyProgram,copyConfig,tripleRegisters_a _ _ _ _ hab had, tripleRegisters_b _ _ _ _ hbd,tripleRegisters_update_a _ _ _ _ hab had,tripleRegisters_update_b _ _ _ _ hbd] rw [List.length_cons,show 2*(xs.length+1)+1=2+(2*xs.length+1) by omega,execution_add,ht,ih] simp only [List.reverse_cons,List.append_assoc,List.singleton_append] congr 1 ; omega lemma copy_restore (a b d : Fin (k+8)) (hab : a≠b) (had : a≠d) (hbd : b≠d) (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) (xs ys zs : List Bool) (q c : ℕ) (bits : ℕ → Bool) : execution (copyProgram a b d) O (copyConfig (tripleRegisters R a b d xs ys zs) 3 q c) bits (3*ys.length+1)=copyConfig (tripleRegisters R a b d (ys.reverse++xs) [] (ys.reverse++zs)) 8 q (c+3*ys.length+1) := by induction ys generalizing xs zs c bits with | nil => simp [execution,machineStep,copyProgram,copyConfig,tripleRegisters_b _ _ _ _ hbd] | cons y ys ih => have ht : execution (copyProgram a b d) O (copyConfig (tripleRegisters R a b d xs (y::ys) zs) 3 q c) bits 3= copyConfig (tripleRegisters R a b d (y::xs) ys (y::zs)) 3 q (c+3) := by cases y <;> simp [execution,machineStep,copyProgram,copyConfig,tripleRegisters_a _ _ _ _ hab had, tripleRegisters_b _ _ _ _ hbd,tripleRegisters_d,tripleRegisters_update_a _ _ _ _ hab had, tripleRegisters_update_b _ _ _ _ hbd,tripleRegisters_update_d] rw [List.length_cons,show 3*(ys.length+1)+1=3+(3*ys.length+1) by omega,execution_add,ht,ih] simp only [List.reverse_cons,List.append_assoc,List.singleton_append] congr 1 ; omega theorem copy_block (a b d : Fin (k+8)) (hab : a≠b) (had : a≠d) (hbd : b≠d) (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) (xs zs : List Bool) (q c : ℕ) (bits : ℕ → Bool) : execution (copyProgram a b d) O (copyConfig (tripleRegisters R a b d xs [] zs) 0 q c) bits (5*xs.length+2)=copyConfig (tripleRegisters R a b d xs [] (xs++zs)) 8 q (c+5*xs.length+2) := by rw [show 5*xs.length+2=(2*xs.length+1)+(3*xs.length+1) by omega,execution_add, copy_scan a b d hab had hbd] simp only [List.append_nil] rw [←List.length_reverse (as:=xs),copy_restore a b d hab had hbd] simp only [List.reverse_reverse,List.length_reverse,List.append_nil] congr 1 ; omega def sumDigit (x y c : Bool) : Bool := xor (xor x y) c def sumCarry (x y c : Bool) : Bool := (x && y) || (x && c) || (y && c) def addDigits (c : Bool) (xs ys : List Bool) : List Bool := match xs,ys with | [],[] => if c then [true] else [] | x::xs,[] => sumDigit x false c :: addDigits (sumCarry x false c) xs [] | [],y::ys => sumDigit false y c :: addDigits (sumCarry false y c) [] ys | x::xs,y::ys => sumDigit x y c :: addDigits (sumCarry x y c) xs ys termination_by xs.length+ys.length def addCost (c : Bool) (xs ys : List Bool) : ℕ := match xs,ys with | [],[] => if c then 3 else 2 | x::xs,[] => 3+addCost (sumCarry x false c) xs [] | [],y::ys => 3+addCost (sumCarry false y c) [] ys | x::xs,y::ys => 3+addCost (sumCarry x y c) xs ys termination_by xs.length+ys.length lemma addDigits_value (c : Bool) (xs ys : List Bool) : binaryValue (addDigits c xs ys)=binaryValue xs+binaryValue ys+(if c then 1 else 0) := by induction xs generalizing ys c with | nil => induction ys generalizing c with | nil => cases c <;> simp [addDigits,binaryValue] | cons y ys ih => simp only [addDigits,binaryValue,ih] cases y <;> cases c <;> simp [sumDigit,sumCarry] <;> omega | cons x xs ih => cases ys with | nil => simp only [addDigits,binaryValue,ih] cases x <;> cases c <;> simp [sumDigit,sumCarry] <;> omega | cons y ys => simp only [addDigits,binaryValue,ih] cases x <;> cases y <;> cases c <;> simp [sumDigit,sumCarry] <;> omega lemma addDigits_length_cost (c : Bool) (xs ys : List Bool) : (addDigits c xs ys).length≤xs.length+ys.length+1 ∧ addCost c xs ys≤3*(xs.length+ys.length)+3 := by induction xs generalizing ys c with | nil => induction ys generalizing c with | nil => cases c <;> simp [addDigits,addCost] | cons y ys ih => have hi := ih (sumCarry false y c) simp only [addDigits,addCost,List.length_cons,List.length_nil] at * constructor <;> omega | cons x xs ih => cases ys with | nil => have hi := ih (sumCarry x false c) [] simp only [addDigits,addCost,List.length_cons,List.length_nil] at * constructor <;> omega | cons y ys => have hi := ih (sumCarry x y c) ys simp only [addDigits,addCost,List.length_cons] at * constructor <;> omega def addConfig (R : Fin (k+8) → List Bool) (pc : Fin 17) (q c : ℕ) : MachineConfig k 16 := ⟨R,pc,none,q,c⟩ def addProgram (a b d : Fin (k+8)) : Program k 16 := fun pc => match pc.val with | 0 => .pop a 2 3 4 | 1 => .pop a 5 6 7 | 2 => .pop b 12 8 9 | 3 => .pop b 8 8 9 | 4 => .pop b 9 9 10 | 5 => .pop b 13 9 10 | 6 => .pop b 9 9 10 | 7 => .pop b 10 10 11 | 8 => .push d false 0 | 9 => .push d true 0 | 10 => .push d false 1 | 11 => .push d true 1 | 12 => .pop d 16 14 15 | 13 => .push d true 12 | 14 => .push a false 12 | 15 => .push a true 12 | _ => .halt lemma add_build (a b d : Fin (k+8)) (hab : a≠b) (had : a≠d) (hbd : b≠d) (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) (xs ys zs : List Bool) (carry : Bool) (q c : ℕ) (bits : ℕ → Bool) : execution (addProgram a b d) O (addConfig (tripleRegisters R a b d xs ys zs) (if carry then 1 else 0) q c) bits (addCost carry xs ys)=addConfig (tripleRegisters R a b d [] [] ((addDigits carry xs ys).reverse++zs)) 12 q (c+addCost carry xs ys) := by induction xs generalizing ys zs carry c bits with | nil => induction ys generalizing zs carry c bits with | nil => cases carry <;> simp [addCost,addDigits,execution,machineStep,addProgram,addConfig, tripleRegisters_a _ _ _ _ hab had,tripleRegisters_b _ _ _ _ hbd,tripleRegisters_d, tripleRegisters_update_d] | cons y ys ih => have ht : execution (addProgram a b d) O (addConfig (tripleRegisters R a b d [] (y::ys) zs) (if carry then 1 else 0) q c) bits 3= addConfig (tripleRegisters R a b d [] ys (sumDigit false y carry::zs)) (if sumCarry false y carry then 1 else 0) q (c+3) := by cases y <;> cases carry <;> simp [execution,machineStep,addProgram,addConfig,sumDigit,sumCarry, tripleRegisters_a _ _ _ _ hab had,tripleRegisters_b _ _ _ _ hbd,tripleRegisters_d, tripleRegisters_update_b _ _ _ _ hbd,tripleRegisters_update_d] rw [addCost,execution_add,ht,ih] simp only [addDigits,List.reverse_cons,List.append_assoc,List.singleton_append] congr 1 ; omega | cons x xs ih => cases ys with | nil => have ht : execution (addProgram a b d) O (addConfig (tripleRegisters R a b d (x::xs) [] zs) (if carry then 1 else 0) q c) bits 3= addConfig (tripleRegisters R a b d xs [] (sumDigit x false carry::zs)) (if sumCarry x false carry then 1 else 0) q (c+3) := by cases x <;> cases carry <;> simp [execution,machineStep,addProgram,addConfig,sumDigit,sumCarry, tripleRegisters_a _ _ _ _ hab had,tripleRegisters_b _ _ _ _ hbd,tripleRegisters_d, tripleRegisters_update_a _ _ _ _ hab had,tripleRegisters_update_d] rw [addCost,execution_add,ht,ih] simp only [addDigits,List.reverse_cons,List.append_assoc,List.singleton_append] congr 1 ; omega | cons y ys => have ht : execution (addProgram a b d) O (addConfig (tripleRegisters R a b d (x::xs) (y::ys) zs) (if carry then 1 else 0) q c) bits 3= addConfig (tripleRegisters R a b d xs ys (sumDigit x y carry::zs)) (if sumCarry x y carry then 1 else 0) q (c+3) := by cases x <;> cases y <;> cases carry <;> simp [execution,machineStep,addProgram,addConfig,sumDigit,sumCarry, tripleRegisters_a _ _ _ _ hab had,tripleRegisters_b _ _ _ _ hbd,tripleRegisters_d, tripleRegisters_update_a _ _ _ _ hab had,tripleRegisters_update_b _ _ _ _ hbd, tripleRegisters_update_d] rw [addCost,execution_add,ht,ih] simp only [addDigits,List.reverse_cons,List.append_assoc,List.singleton_append] congr 1 ; omega lemma add_restore (a b d : Fin (k+8)) (hab : a≠b) (had : a≠d) (_ : b≠d) (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) (xs ys zs : List Bool) (q c : ℕ) (bits : ℕ → Bool) : execution (addProgram a b d) O (addConfig (tripleRegisters R a b d xs ys zs) 12 q c) bits (2*zs.length+1)=addConfig (tripleRegisters R a b d (zs.reverse++xs) ys []) 16 q (c+2*zs.length+1) := by induction zs generalizing xs c bits with | nil => simp [execution,machineStep,addProgram,addConfig,tripleRegisters_d] | cons z zs ih => have ht : execution (addProgram a b d) O (addConfig (tripleRegisters R a b d xs ys (z::zs)) 12 q c) bits 2= addConfig (tripleRegisters R a b d (z::xs) ys zs) 12 q (c+2) := by cases z <;> simp [execution,machineStep,addProgram,addConfig,tripleRegisters_a _ _ _ _ hab had, tripleRegisters_d,tripleRegisters_update_a _ _ _ _ hab had,tripleRegisters_update_d] rw [List.length_cons,show 2*(zs.length+1)+1=2+(2*zs.length+1) by omega,execution_add,ht,ih] simp only [List.reverse_cons,List.append_assoc,List.singleton_append] congr 1 ; omega theorem addition_block (a b d : Fin (k+8)) (hab : a≠b) (had : a≠d) (hbd : b≠d) (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) (xs ys : List Bool) (q c : ℕ) (bits : ℕ → Bool) : let z := addDigits false xs ys let t := addCost false xs ys+2*z.length+1 binaryValue z=binaryValue xs+binaryValue ys ∧ t≤5*(xs.length+ys.length)+6 ∧ execution (addProgram a b d) O (addConfig (tripleRegisters R a b d xs ys []) 0 q c) bits t= addConfig (tripleRegisters R a b d z [] []) 16 q (c+t) := by dsimp only refine ⟨by simpa using addDigits_value false xs ys,?_,?_⟩ · have h := addDigits_length_cost false xs ys omega · rw [show addCost false xs ys+2*(addDigits false xs ys).length+1= addCost false xs ys+(2*(addDigits false xs ys).length+1) by omega,execution_add] rw [show (0 : Fin 17)=(if false then 1 else 0) by rfl,add_build a b d hab had hbd] simp only [List.append_nil] rw [←List.length_reverse (as:=addDigits false xs ys),add_restore a b d hab had hbd] simp only [List.reverse_reverse,List.length_reverse,List.append_nil] congr 1 ; omega lemma addDigits_length_max (c : Bool) (xs ys : List Bool) : (addDigits c xs ys).length≤ max xs.length ys.length+1 := by induction xs generalizing c ys with | nil => induction ys generalizing c with | nil => cases c <;> simp [addDigits] | cons y ys ih => have h := ih (sumCarry false y c) simp only [addDigits,List.length_cons,List.length_nil,Nat.zero_max] at * omega | cons x xs ih => cases ys with | nil => have h := ih (sumCarry x false c) [] simp only [addDigits,List.length_cons,List.length_nil,Nat.max_zero] at * omega | cons y ys => have h := ih (sumCarry x y c) ys simp only [addDigits,List.length_cons] at * omega lemma workReg_ne {a b : ℕ} (ha : a if i=0 then xs else if i=1 then ys else if i=2 then zs else if i=3 then [] else if i=4 then ws else R i lemma mulRegisters_copy_in (R : Fin (k+8) → List Bool) (xs ys zs : List Bool) : tripleRegisters (mulRegisters R xs ys zs []) 0 3 4 xs [] []=mulRegisters R xs ys zs [] := by funext i by_cases h0 : i=0 <;> by_cases h3 : i=3 <;> by_cases h4 : i=4 <;> simp_all [tripleRegisters,pairRegisters,mulRegisters] lemma mulRegisters_copy_out (R : Fin (k+8) → List Bool) (xs ys zs : List Bool) : tripleRegisters (mulRegisters R xs ys zs []) 0 3 4 xs [] xs=mulRegisters R xs ys zs xs := by funext i by_cases h0 : i=0 <;> by_cases h3 : i=3 <;> by_cases h4 : i=4 <;> simp_all [tripleRegisters,pairRegisters,mulRegisters] lemma mulRegisters_add_in (R : Fin (k+8) → List Bool) (xs ys zs : List Bool) : tripleRegisters (mulRegisters R xs ys zs xs) 2 4 3 zs xs []=mulRegisters R xs ys zs xs := by funext i by_cases h2 : i=2 <;> by_cases h3 : i=3 <;> by_cases h4 : i=4 <;> simp_all [tripleRegisters,pairRegisters,mulRegisters] lemma mulRegisters_add_out (R : Fin (k+8) → List Bool) (xs ys zs us : List Bool) : tripleRegisters (mulRegisters R xs ys zs xs) 2 4 3 us [] []=mulRegisters R xs ys us [] := by funext i by_cases h2 : i=2 <;> by_cases h3 : i=3 <;> by_cases h4 : i=4 <;> simp_all [tripleRegisters,pairRegisters,mulRegisters] lemma mulRegisters_update0 (R : Fin (k+8) → List Bool) (xs ys zs ws us : List Bool) : Function.update (mulRegisters R xs ys zs ws) 0 us=mulRegisters R us ys zs ws := by funext i by_cases h0 : i=0 <;> simp [mulRegisters,h0] lemma mulRegisters_update1 (R : Fin (k+8) → List Bool) (xs ys zs ws us : List Bool) : Function.update (mulRegisters R xs ys zs ws) 1 us=mulRegisters R xs us zs ws := by funext i by_cases h0 : i=0 <;> by_cases h1 : i=1 <;> simp_all [mulRegisters] def mulBody : Program k 24 := concatProgram (copyProgram 0 3 4) (addProgram 2 4 3) def mulBodyConfig (R : Fin (k+8) → List Bool) (pc : Fin 25) (q c : ℕ) : MachineConfig k 24 := ⟨R,pc,none,q,c⟩ def mulBodyCost (xs zs : List Bool) : ℕ := (5*xs.length+2)+(addCost false zs xs+2*(addDigits false zs xs).length+1) lemma mulBody_exit : (mulBody : Program k 24) (lastLabel 24)=.halt := by simp [mulBody,concatProgram,lastLabel,addProgram,Instruction.relabel] lemma mulBody_run (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) (xs ys zs : List Bool) (q c : ℕ) (bits : ℕ → Bool) : execution mulBody O (mulBodyConfig (mulRegisters R xs ys zs []) 0 q c) bits (mulBodyCost xs zs)= mulBodyConfig (mulRegisters R xs ys (addDigits false zs xs) []) 24 q (c+mulBodyCost xs zs) := by have hc := copy_block (k:=k) (0 : Fin (k+8)) 3 4 (by simp) (by simp) (by simp) O (mulRegisters R xs ys zs []) xs [] q c bits simp only [List.append_nil,mulRegisters_copy_in,mulRegisters_copy_out] at hc have ha := (addition_block (k:=k) (2 : Fin (k+8)) 4 3 (by simp) (by simp) (by simp) O (mulRegisters R xs ys zs xs) zs xs q (c+(5*xs.length+2)) (fun i => bits (5*xs.length+2+i))).2.2 simp only [mulRegisters_add_in,mulRegisters_add_out] at ha have hh := concat_run (copyProgram (k:=k) 0 3 4) (addProgram 2 4 3) (by rfl) O (copyConfig (mulRegisters R xs ys zs []) 0 q c) bits (5*xs.length+2) (addCost false zs xs+2*(addDigits false zs xs).length+1) (by rw [hc]; rfl) (by rw [hc]; rfl) rw [hc] at hh have hre : restartControl (copyConfig (mulRegisters R xs ys zs xs) 8 q (c+5*xs.length+2)) (0 : Fin 17)=addConfig (mulRegisters R xs ys zs xs) 0 q (c+(5*xs.length+2)) := by simp [restartControl,copyConfig,addConfig,Nat.add_assoc] rw [hre,ha] at hh simpa [mulBody,mulBodyCost,mulBodyConfig,copyConfig,addConfig,relabelConfig,firstLabel,secondLabel, Nat.add_assoc] using hh lemma mulBodyCost_bound (xs zs : List Bool) : mulBodyCost xs zs≤15*max xs.length zs.length+8 := by have h := addDigits_length_cost false zs xs unfold mulBodyCost have hx : xs.length≤ max xs.length zs.length := Nat.le_max_left _ _ have hz : zs.length≤ max xs.length zs.length := Nat.le_max_right _ _ omega def mulBodyLabel (i : Fin 25) : Fin 27 := ⟨i.val+1,by omega⟩ def mulProgram : Program k 26 := fun i => if hi : i.val=0 then .pop 1 26 25 1 else if hj : i.val<25 then ((mulBody : Program k 24) ⟨i.val-1,by omega⟩).relabel mulBodyLabel else if i.val=25 then .push 0 false 0 else .halt def mulConfig (R : Fin (k+8) → List Bool) (pc : Fin 27) (q c : ℕ) : MachineConfig k 26 := ⟨R,pc,none,q,c⟩ lemma mulProgram_body (i : Fin 25) (hi : i≠lastLabel 24) : (mulProgram : Program k 26) (mulBodyLabel i)=((mulBody : Program k 24) i).relabel mulBodyLabel := by have h : i.val<24 := by have hh : i.val≠24 := by intro hh; apply hi; exact Fin.ext hh omega simp [mulProgram,mulBodyLabel,show i.val+1<25 by omega] lemma mulProgram_body_run (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) (xs ys zs : List Bool) (q c : ℕ) (bits : ℕ → Bool) : execution mulProgram O (mulConfig (mulRegisters R xs ys zs []) 1 q c) bits (mulBodyCost xs zs)= mulConfig (mulRegisters R xs ys (addDigits false zs xs) []) 25 q (c+mulBodyCost xs zs) := by have h := execution_relabel_before_halt (mulBody : Program k 24) mulProgram mulBodyLabel (lastLabel 24) mulBody_exit mulProgram_body O (mulBodyConfig (mulRegisters R xs ys zs []) 0 q c) bits (mulBodyCost xs zs) (by rw [mulBody_run]; rfl) rw [mulBody_run] at h simpa [relabelConfig,mulBodyConfig,mulConfig,mulBodyLabel] using h def mulDigits (xs ys zs : List Bool) : List Bool := match ys with | [] => zs | bit::ys => mulDigits (false::xs) ys (if bit then addDigits false zs xs else zs) def mulCost (xs ys zs : List Bool) : ℕ := match ys with | [] => 1 | bit::ys => 2+(if bit then mulBodyCost xs zs else 0)+ mulCost (false::xs) ys (if bit then addDigits false zs xs else zs) lemma mulDigits_value (xs ys zs : List Bool) : binaryValue (mulDigits xs ys zs)=binaryValue zs+binaryValue xs*binaryValue ys := by induction ys generalizing xs zs with | nil => simp [mulDigits,binaryValue] | cons bit ys ih => simp only [mulDigits,ih] cases bit <;> simp [binaryValue,addDigits_value] <;> ring lemma mulDigits_length (xs ys zs : List Bool) : (mulDigits xs ys zs).length≤ max xs.length zs.length+ys.length := by induction ys generalizing xs zs with | nil => simp [mulDigits] | cons bit ys ih => have h1 := ih (false::xs) (if bit then addDigits false zs xs else zs) have h2 := addDigits_length_max false zs xs cases bit <;> simp only [mulDigits,Bool.false_eq_true,ite_false,ite_true,List.length_cons] at * <;> omega lemma mulCost_bound (xs ys zs : List Bool) : mulCost xs ys zs≤(15*(max xs.length zs.length+ys.length)+10)*ys.length+1 := by induction ys generalizing xs zs with | nil => simp [mulCost] | cons bit ys ih => have h1 := ih (false::xs) (if bit then addDigits false zs xs else zs) have h2 := addDigits_length_max false zs xs have h3 := mulBodyCost_bound xs zs have hz : (if bit then addDigits false zs xs else zs).length≤ max xs.length zs.length+1 := by cases bit <;> simp only [Bool.false_eq_true,ite_false,ite_true] <;> omega have hh : max (false::xs).length (if bit then addDigits false zs xs else zs).length≤ max xs.length zs.length+1 := by simp only [List.length_cons]; omega have hm : (15*(max (false::xs).length (if bit then addDigits false zs xs else zs).length+ys.length)+10)*ys.length≤ (15*(max xs.length zs.length+1+ys.length)+10)*ys.length := Nat.mul_le_mul_right _ (by omega) cases bit <;> simp only [mulCost,Bool.false_eq_true,ite_false,ite_true,List.length_cons] at * <;> nlinarith lemma mul_run (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) (xs ys zs : List Bool) (q c : ℕ) (bits : ℕ → Bool) : execution mulProgram O (mulConfig (mulRegisters R xs ys zs []) 0 q c) bits (mulCost xs ys zs)= mulConfig (mulRegisters R (List.replicate ys.length false++xs) [] (mulDigits xs ys zs) []) 26 q (c+mulCost xs ys zs) := by induction ys generalizing xs zs c bits with | nil => simp [mulCost,mulDigits,execution,machineStep,mulProgram,mulConfig,mulRegisters] | cons bit ys ih => have hpop : execution mulProgram O (mulConfig (mulRegisters R xs (bit::ys) zs []) 0 q c) bits 1= mulConfig (mulRegisters R xs ys zs []) (if bit then 1 else 25) q (c+1) := by cases bit <;> simp [execution,machineStep,mulProgram,mulConfig,mulRegisters_update1,mulRegisters] have hshift (us : List Bool) (c' : ℕ) (bits' : ℕ → Bool) : execution mulProgram O (mulConfig (mulRegisters R xs ys us []) 25 q c') bits' 1= mulConfig (mulRegisters R (false::xs) ys us []) 0 q (c'+1) := by simp [execution,machineStep,mulProgram,mulConfig,mulRegisters_update0,mulRegisters] have hbody : execution mulProgram O (mulConfig (mulRegisters R xs (bit::ys) zs []) 0 q c) bits (2+(if bit then mulBodyCost xs zs else 0))= mulConfig (mulRegisters R (false::xs) ys (if bit then addDigits false zs xs else zs) []) 0 q (c+(2+(if bit then mulBodyCost xs zs else 0))) := by cases bit with | false => simp only [Bool.false_eq_true,ite_false,Nat.add_zero] rw [show 2=1+1 by rfl,execution_add,hpop] simp only [Bool.false_eq_true,ite_false] rw [hshift] | true => simp only [ite_true] rw [show 2+mulBodyCost xs zs=1+(mulBodyCost xs zs+1) by omega, execution_add,hpop] simp only [ite_true] rw [execution_add,mulProgram_body_run,hshift] try (congr 1 ; omega) rw [mulCost,execution_add,hbody,ih] simp only [mulDigits,List.length_cons,List.replicate_add,List.replicate_one,List.append_assoc,List.singleton_append] congr 1 ; omega theorem multiplication_block (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) (xs ys : List Bool) (q c : ℕ) (bits : ℕ → Bool) : let z := mulDigits xs ys [] let t := mulCost xs ys [] binaryValue z=binaryValue xs*binaryValue ys ∧ t≤(15*(xs.length+ys.length)+10)*ys.length+1 ∧ execution mulProgram O (mulConfig (mulRegisters R xs ys [] []) 0 q c) bits t= mulConfig (mulRegisters R (List.replicate ys.length false++xs) [] z []) 26 q (c+t) := by refine ⟨by simp [mulDigits_value,binaryValue],?_,mul_run O R xs ys [] q c bits⟩ simpa using mulCost_bound xs ys [] def coinWord : ℕ → (ℕ → Bool) → List Bool | 0,_ => [] | m+1,bits => bits 1::coinWord m (fun i => bits (3+i)) lemma coinWord_length (m : ℕ) (bits : ℕ → Bool) : (coinWord m bits).length=m := by induction m generalizing bits with | zero => rfl | succ m ih => simp [coinWord,ih] lemma coinWord_ofFn (m : ℕ) (bits : ℕ → Bool) : coinWord m bits=List.ofFn (fun i : Fin m => bits (3*i.val+1)) := by induction m generalizing bits with | zero => simp [coinWord] | succ m ih => rw [coinWord,ih,List.ofFn_succ] simp only [Fin.val_zero,Nat.mul_zero,Nat.zero_add,Fin.val_succ] congr 2 funext i congr 1 ; omega def randomConfig (R : Fin (k+8) → List Bool) (pc : Fin 5) (q c : ℕ) : MachineConfig k 4 := ⟨R,pc,none,q,c⟩ def randomProgram (counter dest : Fin (k+8)) : Program k 4 := fun pc => match pc.val with | 0 => .pop counter 4 1 1 | 1 => .coin 2 3 | 2 => .push dest false 0 | 3 => .push dest true 0 | _ => .halt theorem random_bank_block (a b : Fin (k+8)) (hab : a≠b) (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) (xs ys : List Bool) (q c : ℕ) (bits : ℕ → Bool) : execution (randomProgram a b) O (randomConfig (pairRegisters R a b xs ys) 0 q c) bits (3*xs.length+1)= randomConfig (pairRegisters R a b [] ((coinWord xs.length bits).reverse++ys)) 4 q (c+3*xs.length+1) := by induction xs generalizing ys c bits with | nil => simp [execution,machineStep,randomProgram,randomConfig,pairRegisters_a _ _ _ hab,coinWord] | cons x xs ih => have ht : execution (randomProgram a b) O (randomConfig (pairRegisters R a b (x::xs) ys) 0 q c) bits 3= randomConfig (pairRegisters R a b xs (bits 1::ys)) 0 q (c+3) := by cases x <;> cases hb : bits 1 <;> simp [execution,machineStep,randomProgram,randomConfig,pairRegisters_a _ _ _ hab, pairRegisters_b,pairRegisters_update_a _ _ _ hab,pairRegisters_update_b,hb] rw [List.length_cons,show 3*(xs.length+1)+1=3+(3*xs.length+1) by omega,execution_add,ht,ih] simp only [coinWord,List.reverse_cons,List.append_assoc,List.singleton_append] congr 1 ; omega end lemma bitResourceParameter_le_target (n r : ℕ) (ε δ : ℚ) : bitResourceParameter n ε δ≤1+n+inputLength n r ε δ+⌈ε⁻¹⌉₊+Nat.clog 2 ⌈δ⁻¹⌉₊ := by unfold bitResourceParameter inputLength omega lemma fairBitCount_le_target (n r : ℕ) (ε δ : ℚ) : fairBitCount n ε δ≤resourceBound (10^66) 73 n r ε δ := by have h := fairBitCount_polynomial n ε δ exact h.trans (Nat.mul_le_mul_left _ (Nat.pow_le_pow_left (bitResourceParameter_le_target n r ε δ) _)) lemma queryCount_le_target (n r : ℕ) (ε δ : ℚ) : 10^31*(bitResourceParameter n ε δ)^30≤resourceBound (10^66) 73 n r ε δ := by have ha := bitResourceParameter_le_target n r ε δ have hb : 1≤1+n+inputLength n r ε δ+⌈ε⁻¹⌉₊+Nat.clog 2 ⌈δ⁻¹⌉₊ := by omega unfold resourceBound apply Nat.mul_le_mul (by norm_num : (10:ℕ)^31≤10^66) exact (Nat.pow_le_pow_left ha 30).trans (Nat.pow_le_pow_right hb (by decide : 30≤73)) theorem query_experiment_target_scale (n r : ℕ) (O : IndependenceOracle n) (M₁ M₂ : Matroid (Fin n)) (hO : ExactOracles M₁ M₂ O) (hE₁ : M₁.E=Set.univ) (hE₂ : M₂.E=Set.univ) (hr₁ : M₁.eRank=(r:ℕ∞)) (hr₂ : M₂.eRank=(r:ℕ∞)) (ε δ : ℚ) (hε0 : 0<ε) (hε1 : ε<1) (hδ : 0<δ) : let B := resourceBound (10^66) 73 n r ε δ let out := paddedQueryOutput n r O ε δ B (fairBitCount_le_target n r ε δ) (∀ bits,0≤(out bits).1 ∧ (commonBaseCount M₁ M₂=0 → (out bits).1=0) ∧ (out bits).2≤B) ∧ (1-δ)*(2:ℚ)^B≤(Nat.card {bits : BitWord B // relativeAccuracy ε (commonBaseCount M₁ M₂) (out bits).1}:ℚ) := by dsimp only have h := query_fair_experiment n r O M₁ M₂ hO hE₁ hE₂ hr₁ hr₂ ε δ hε0 hε1 hδ (resourceBound (10^66) 73 n r ε δ) (fairBitCount_le_target n r ε δ) refine ⟨?_,h.2⟩ intro bits exact ⟨(h.1 bits).1,(h.1 bits).2.1,(h.1 bits).2.2.trans (queryCount_le_target n r ε δ)⟩ open scoped Classical lemma uniformAverage_bitEmbedding (m B : ℕ) (f : Fin m → Fin B) (hf : Function.Injective f) (φ : BitWord m → ℝ) : uniformAverage (fun w : BitWord B => φ (fun i => w (f i)))=uniformAverage φ := by have hm : m≤B := by simpa using Fintype.card_le_of_injective f hf let g : Fin m → Fin B := fun i => ⟨i.val,lt_of_lt_of_le i.isLt hm⟩ have hg : Function.Injective g := by intro i j h apply Fin.ext exact congrArg (fun x : Fin B => x.val) h obtain ⟨σ,hσ⟩ := Equiv.Perm.exists_extending_pair g f hg hf let e : BitWord B ≃ BitWord B := Equiv.arrowCongr σ.symm (Equiv.refl Bool) have he (w : BitWord B) : (fun i => w (f i))=bitPrefix m B hm (e w) := by funext i change w (f i)=w (σ (g i)) rw [hσ] simp_rw [he] rw [uniformAverage_equiv e (fun w => φ (bitPrefix m B hm w))] exact uniformAverage_bitPrefix m B hm φ def clockPosition (start m B : ℕ) (h : start+3*m+1≤B) (i : Fin m) : Fin B := ⟨start+3*i.val+1,by have hi:=i.isLt; omega⟩ lemma clockPosition_injective (start m B : ℕ) (h : start+3*m+1≤B) : Function.Injective (clockPosition start m B h) := by intro i j hij have hh := congrArg Fin.val hij dsimp only [clockPosition] at hh apply Fin.ext omega def clockWord (start m B : ℕ) (h : start+3*m+1≤B) (w : BitWord B) : BitWord m := fun i => w (clockPosition start m B h i) lemma clockWord_law (start m B : ℕ) (h : start+3*m+1≤B) (φ : BitWord m → ℝ) : uniformAverage (fun w : BitWord B => φ (clockWord start m B h w))=uniformAverage φ := uniformAverage_bitEmbedding m B _ (clockPosition_injective start m B h) φ noncomputable def clockQueryOutput (n r : ℕ) (O : IndependenceOracle n) (ε δ : ℚ) (start B : ℕ) (h : start+3*fairBitCount n ε δ+1≤B) (w : BitWord B) : ℚ × ℕ := queryBoundedOutput n r O ε δ (bankWordEquiv n ε δ (clockWord start _ B h w)) lemma clockQueryOutput_value (n r : ℕ) (O : IndependenceOracle n) (ε δ : ℚ) (start B : ℕ) (h : start+3*fairBitCount n ε δ+1≤B) (w : BitWord B) : (clockQueryOutput n r O ε δ start B h w).1= flatFPRASOutput n r O ε δ (clockWord start _ B h w) := queryBoundedOutput_value n r O ε δ _ lemma clockQueryOutput_law (n r : ℕ) (O : IndependenceOracle n) (ε δ : ℚ) (start B : ℕ) (h : start+3*fairBitCount n ε δ+1≤B) (φ : ℚ → ℝ) : uniformAverage (fun w : BitWord B => φ (clockQueryOutput n r O ε δ start B h w).1)= uniformAverage (fun w : FPRASBank n ε δ => φ (canonicalBoundedOutput n r O ε δ w)) := by simp_rw [clockQueryOutput_value] rw [clockWord_law start _ B h (fun w => φ (flatFPRASOutput n r O ε δ w))] exact uniformAverage_equiv (bankWordEquiv n ε δ) (fun w : FPRASBank n ε δ => φ (canonicalBoundedOutput n r O ε δ w)) theorem clock_query_experiment (n r : ℕ) (O : IndependenceOracle n) (M₁ M₂ : Matroid (Fin n)) (hO : ExactOracles M₁ M₂ O) (hE₁ : M₁.E=Set.univ) (hE₂ : M₂.E=Set.univ) (hr₁ : M₁.eRank=(r:ℕ∞)) (hr₂ : M₂.eRank=(r:ℕ∞)) (ε δ : ℚ) (hε0 : 0<ε) (hε1 : ε<1) (hδ : 0<δ) (start B : ℕ) (hB : start+3*fairBitCount n ε δ+1≤B) : (∀ bits : BitWord B, let out := clockQueryOutput n r O ε δ start B hB bits 0≤out.1 ∧ (commonBaseCount M₁ M₂=0 → out.1=0) ∧ out.2≤10^31*(bitResourceParameter n ε δ)^30) ∧ (1-δ)*(2:ℚ)^B≤(Nat.card {bits : BitWord B // relativeAccuracy ε (commonBaseCount M₁ M₂) (clockQueryOutput n r O ε δ start B hB bits).1}:ℚ) := by have hf := canonical_bounded_fair_experiment n r O M₁ M₂ hO hE₁ hE₂ hr₁ hr₂ ε δ hε0 hε1 hδ constructor · intro bits refine ⟨?_,?_,queryBoundedOutput_queries n r O ε δ _⟩ · exact (hf.1 _).1.trans_eq (queryBoundedOutput_value n r O ε δ _).symm · intro hZ exact (queryBoundedOutput_value n r O ε δ _).trans ((hf.1 _).2 hZ) · have h := hf.2 rw [←clockQueryOutput_law n r O ε δ start B hB (fun z => if relativeAccuracy ε (commonBaseCount M₁ M₂) z then (1:ℝ) else 0)] at h rw [uniformAverage_indicator_card] at h have hcard : Fintype.card (BitWord B)=2^B := by simp [BitWord] rw [hcard,Nat.cast_pow,Nat.cast_ofNat] at h have hh := (le_div_iff₀ (by positivity : (0:ℝ)<2^B)).mp h exact_mod_cast hh section variable {k n : ℕ} def wordOracle (which : Bool) (O : IndependenceOracle n) (l : List Bool) : Bool := O which (fun i => l[i.val]?.getD false) def wordGreedy (W : List Bool → Bool) : List Bool → List Bool → List Bool | [],ps => ps | b::xs,ps => wordGreedy W xs ((b && W (List.replicate xs.length false++true::ps))::ps) def greedyTime (n : ℕ) : List Bool → ℕ | [] => 1 | b::xs => (if b then 6*n+5 else 3)+greedyTime n xs def greedyWork (n : ℕ) : List Bool → ℕ | [] => 1 | b::xs => (if b then 8*n+5 else 3)+greedyWork n xs def greedyCalls : List Bool → ℕ | [] => 0 | b::xs => (if b then 1 else 0)+greedyCalls xs lemma greedyTime_bound (n : ℕ) (xs : List Bool) : greedyTime n xs≤(6*n+5)*xs.length+1 := by induction xs with | nil => simp [greedyTime] | cons b xs ih => cases b <;> simp only [greedyTime,List.length_cons,Bool.false_eq_true,ite_false,ite_true] <;> nlinarith lemma greedyWork_bound (n : ℕ) (xs : List Bool) : greedyWork n xs≤(8*n+5)*xs.length+1 := by induction xs with | nil => simp [greedyWork] | cons b xs ih => cases b <;> simp only [greedyWork,List.length_cons,Bool.false_eq_true,ite_false,ite_true] <;> nlinarith lemma greedyCalls_bound (xs : List Bool) : greedyCalls xs≤xs.length := by induction xs with | nil => simp [greedyCalls] | cons b xs ih => cases b <;> simp_all [greedyCalls] <;> omega lemma wordGreedy_length (W : List Bool → Bool) (xs ps : List Bool) : (wordGreedy W xs ps).length=xs.length+ps.length := by induction xs generalizing ps with | nil => simp [wordGreedy] | cons b xs ih => simp [wordGreedy,ih,Nat.add_comm,Nat.add_left_comm] def greedyRegisters (R : Fin (k+8) → List Bool) (xs zs ps qs : List Bool) : Fin (k+8) → List Bool := fun i => if i=0 then xs else if i=1 then zs else if i=2 then ps else if i=3 then [] else if i=4 then qs else R i lemma greedyRegisters_update0 (R : Fin (k+8) → List Bool) (xs zs ps qs us : List Bool) : Function.update (greedyRegisters R xs zs ps qs) 0 us=greedyRegisters R us zs ps qs := by funext i; by_cases h : i=0 <;> simp_all [greedyRegisters] lemma greedyRegisters_update1 (R : Fin (k+8) → List Bool) (xs zs ps qs us : List Bool) : Function.update (greedyRegisters R xs zs ps qs) 1 us=greedyRegisters R xs us ps qs := by funext i; by_cases h : i=1 <;> simp_all [greedyRegisters] lemma greedyRegisters_update2 (R : Fin (k+8) → List Bool) (xs zs ps qs us : List Bool) : Function.update (greedyRegisters R xs zs ps qs) 2 us=greedyRegisters R xs zs us qs := by funext i; by_cases h : i=2 <;> simp_all [greedyRegisters] lemma greedyRegisters_update4 (R : Fin (k+8) → List Bool) (xs zs ps qs us : List Bool) : Function.update (greedyRegisters R xs zs ps qs) 4 us=greedyRegisters R xs zs ps us := by funext i; by_cases h : i=4 <;> simp_all [greedyRegisters] def greedyConfig (R : Fin (k+8) → List Bool) (pc : Fin 27) (q c : ℕ) : MachineConfig k 26 := ⟨R,pc,none,q,c⟩ def greedyCopy₁ (i : Fin 9) : Fin 27 := ⟨i.val+4,by omega⟩ def greedyCopy₂ (i : Fin 9) : Fin 27 := ⟨i.val+13,by omega⟩ def greedyProgram (which : Bool) : Program k 26 := fun pc => if h₁ : 4≤pc.val ∧ pc.val<12 then ((copyProgram 2 3 4) ⟨pc.val-4,by omega⟩).relabel greedyCopy₁ else if h₂ : 13≤pc.val ∧ pc.val<21 then ((copyProgram 1 3 4) ⟨pc.val-13,by omega⟩).relabel greedyCopy₂ else match pc.val with | 0 => .pop 0 26 1 2 | 1 => .pop 1 3 3 3 | 2 => .pop 1 4 4 4 | 3 => .push 2 false 0 | 12 => .push 4 true 13 | 21 => .query which 4 22 23 | 22 => .pop 4 24 22 22 | 23 => .pop 4 25 23 23 | 24 => .push 2 false 0 | 25 => .push 2 true 0 | _ => .halt lemma greedy_copy₁ (which : Bool) (i : Fin 9) (hi : i≠8) : greedyProgram (k:=k) which (greedyCopy₁ i)=(copyProgram 2 3 4 i).relabel greedyCopy₁ := by have hh : i.val<8 := by have hb := i.isLt have hn : i.val≠8 := by intro h; exact hi (Fin.ext h) omega simp [greedyProgram,greedyCopy₁,hh,show 4≤ i.val+4 by omega] lemma greedy_copy₂ (which : Bool) (i : Fin 9) (hi : i≠8) : greedyProgram (k:=k) which (greedyCopy₂ i)=(copyProgram 1 3 4 i).relabel greedyCopy₂ := by have hh : i.val<8 := by have hb := i.isLt have hn : i.val≠8 := by intro h; exact hi (Fin.ext h) omega simp [greedyProgram,greedyCopy₂,hh,show 13≤ i.val+13 by omega,show ¬i.val+13<12 by omega] lemma greedyRegisters_copy₁ (R : Fin (k+8) → List Bool) (xs zs ps qs : List Bool) : tripleRegisters (greedyRegisters R xs zs ps qs) 2 3 4 ps [] qs=greedyRegisters R xs zs ps qs := by funext i by_cases h2 : i=2 <;> by_cases h3 : i=3 <;> by_cases h4 : i=4 <;> simp_all [tripleRegisters,pairRegisters,greedyRegisters] lemma greedyRegisters_copy₁_out (R : Fin (k+8) → List Bool) (xs zs ps qs : List Bool) : tripleRegisters (greedyRegisters R xs zs ps qs) 2 3 4 ps [] (ps++qs)=greedyRegisters R xs zs ps (ps++qs) := by funext i by_cases h2 : i=2 <;> by_cases h3 : i=3 <;> by_cases h4 : i=4 <;> simp_all [tripleRegisters,pairRegisters,greedyRegisters] lemma greedyRegisters_copy₂ (R : Fin (k+8) → List Bool) (xs zs ps qs : List Bool) : tripleRegisters (greedyRegisters R xs zs ps qs) 1 3 4 zs [] qs=greedyRegisters R xs zs ps qs := by funext i by_cases h1 : i=1 <;> by_cases h3 : i=3 <;> by_cases h4 : i=4 <;> simp_all [tripleRegisters,pairRegisters,greedyRegisters] lemma greedyRegisters_copy₂_out (R : Fin (k+8) → List Bool) (xs zs ps qs : List Bool) : tripleRegisters (greedyRegisters R xs zs ps qs) 1 3 4 zs [] (zs++qs)=greedyRegisters R xs zs ps (zs++qs) := by funext i by_cases h1 : i=1 <;> by_cases h3 : i=3 <;> by_cases h4 : i=4 <;> simp_all [tripleRegisters,pairRegisters,greedyRegisters] lemma greedy_copy₁_run (which : Bool) (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) (xs zs ps qs : List Bool) (q c : ℕ) (bits : ℕ → Bool) : execution (greedyProgram which) O (greedyConfig (greedyRegisters R xs zs ps qs) 4 q c) bits (5*ps.length+2)= greedyConfig (greedyRegisters R xs zs ps (ps++qs)) 12 q (c+5*ps.length+2) := by have hc := copy_block (k:=k) (2 : Fin (k+8)) 3 4 (by simp) (by simp) (by simp) O (greedyRegisters R xs zs ps qs) ps qs q c bits simp only [greedyRegisters_copy₁,greedyRegisters_copy₁_out] at hc have h := execution_relabel_before_halt (copyProgram (k:=k) 2 3 4) (greedyProgram which) greedyCopy₁ 8 (by rfl) (greedy_copy₁ which) O (copyConfig (greedyRegisters R xs zs ps qs) 0 q c) bits (5*ps.length+2) (by rw [hc]; rfl) rw [hc] at h simpa [relabelConfig,copyConfig,greedyConfig,greedyCopy₁] using h lemma greedy_copy₂_run (which : Bool) (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) (xs zs ps qs : List Bool) (q c : ℕ) (bits : ℕ → Bool) : execution (greedyProgram which) O (greedyConfig (greedyRegisters R xs zs ps qs) 13 q c) bits (5*zs.length+2)= greedyConfig (greedyRegisters R xs zs ps (zs++qs)) 21 q (c+5*zs.length+2) := by have hc := copy_block (k:=k) (1 : Fin (k+8)) 3 4 (by simp) (by simp) (by simp) O (greedyRegisters R xs zs ps qs) zs qs q c bits simp only [greedyRegisters_copy₂,greedyRegisters_copy₂_out] at hc have h := execution_relabel_before_halt (copyProgram (k:=k) 1 3 4) (greedyProgram which) greedyCopy₂ 8 (by rfl) (greedy_copy₂ which) O (copyConfig (greedyRegisters R xs zs ps qs) 0 q c) bits (5*zs.length+2) (by rw [hc]; rfl) rw [hc] at h simpa [relabelConfig,copyConfig,greedyConfig,greedyCopy₂] using h lemma greedy_clear (which b : Bool) (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) (xs zs ps qs : List Bool) (q c : ℕ) (bits : ℕ → Bool) : execution (greedyProgram which) O (greedyConfig (greedyRegisters R xs zs ps qs) (if b then 23 else 22) q c) bits (qs.length+1)=greedyConfig (greedyRegisters R xs zs ps []) (if b then 25 else 24) q (c+qs.length+1) := by induction qs generalizing c bits with | nil => cases b <;> simp [execution,machineStep,greedyProgram,greedyConfig,greedyRegisters] | cons a qs ih => have ht : execution (greedyProgram which) O (greedyConfig (greedyRegisters R xs zs ps (a::qs)) (if b then 23 else 22) q c) bits 1= greedyConfig (greedyRegisters R xs zs ps qs) (if b then 23 else 22) q (c+1) := by cases b <;> cases a <;> simp [execution,machineStep,greedyProgram,greedyConfig,greedyRegisters,greedyRegisters_update4] rw [List.length_cons,show qs.length+1+1=1+(qs.length+1) by omega,execution_add,ht,ih] congr 1 ; omega lemma greedy_query_run (which : Bool) (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) (xs zs ps qs : List Bool) (hn : qs.length=n) (q c : ℕ) (bits : ℕ → Bool) : execution (greedyProgram which) O (greedyConfig (greedyRegisters R xs zs ps qs) 21 q c) bits (n+3)= greedyConfig (greedyRegisters R xs zs (wordOracle which O qs::ps) []) 0 (q+1) (c+3*n+3) := by have ht : execution (greedyProgram which) O (greedyConfig (greedyRegisters R xs zs ps qs) 21 q c) bits 1= greedyConfig (greedyRegisters R xs zs ps qs) (if wordOracle which O qs then 23 else 22) (q+1) (c+2*n+1) := by simp [execution,machineStep,greedyProgram,greedyConfig,greedyRegisters,wordOracle,hn,two_mul,Nat.add_assoc] have hp (b : Bool) (c' : ℕ) (bits' : ℕ → Bool) : execution (greedyProgram which) O (greedyConfig (greedyRegisters R xs zs ps []) (if b then 25 else 24) (q+1) c') bits' 1= greedyConfig (greedyRegisters R xs zs (b::ps) []) 0 (q+1) (c'+1) := by cases b <;> simp [execution,machineStep,greedyProgram,greedyConfig,greedyRegisters_update2,greedyRegisters] rw [show n+3=1+((qs.length+1)+1) by omega,execution_add,ht,execution_add,greedy_clear,hp] congr 1 ; omega lemma greedy_true_body (which : Bool) (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) (xs ps : List Bool) (hn : xs.length+ps.length+1=n) (q c : ℕ) (bits : ℕ → Bool) : execution (greedyProgram which) O (greedyConfig (greedyRegisters R (true::xs) (List.replicate (xs.length+1) false) ps []) 0 q c) bits (6*n+5)= greedyConfig (greedyRegisters R xs (List.replicate xs.length false) (wordOracle which O (List.replicate xs.length false++true::ps)::ps) []) 0 (q+1) (c+8*n+5) := by let zs := List.replicate xs.length false have hpop : execution (greedyProgram which) O (greedyConfig (greedyRegisters R (true::xs) (List.replicate (xs.length+1) false) ps []) 0 q c) bits 2= greedyConfig (greedyRegisters R xs zs ps []) 4 q (c+2) := by simp [execution,machineStep,greedyProgram,greedyConfig,greedyRegisters_update0,greedyRegisters_update1, greedyRegisters,List.replicate_succ,zs] have hpush (c' : ℕ) (bits' : ℕ → Bool) : execution (greedyProgram which) O (greedyConfig (greedyRegisters R xs zs ps ps) 12 q c') bits' 1= greedyConfig (greedyRegisters R xs zs ps (true::ps)) 13 q (c'+1) := by simp [execution,machineStep,greedyProgram,greedyConfig,greedyRegisters_update4,greedyRegisters] have hlen : (zs++true::ps).length=n := by simp only [List.length_append,List.length_cons,List.length_replicate,zs]; omega rw [show 6*n+5=2+((5*ps.length+2)+(1+((5*zs.length+2)+(n+3)))) by simp only [zs,List.length_replicate]; omega, execution_add,hpop,execution_add,greedy_copy₁_run] simp only [List.append_nil] rw [execution_add,hpush,execution_add,greedy_copy₂_run,greedy_query_run _ _ _ _ _ _ _ hlen] congr 1 ; simp only [zs,List.length_replicate] ; omega lemma greedy_false_body (which : Bool) (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) (xs ps : List Bool) (q c : ℕ) (bits : ℕ → Bool) : execution (greedyProgram which) O (greedyConfig (greedyRegisters R (false::xs) (List.replicate (xs.length+1) false) ps []) 0 q c) bits 3= greedyConfig (greedyRegisters R xs (List.replicate xs.length false) (false::ps) []) 0 q (c+3) := by simp [execution,machineStep,greedyProgram,greedyConfig,greedyRegisters_update0,greedyRegisters_update1, greedyRegisters_update2,greedyRegisters,List.replicate_succ] theorem greedy_machine_run (which : Bool) (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) (xs ps : List Bool) (hn : xs.length+ps.length=n) (q c : ℕ) (bits : ℕ → Bool) : execution (greedyProgram which) O (greedyConfig (greedyRegisters R xs (List.replicate xs.length false) ps []) 0 q c) bits (greedyTime n xs)= greedyConfig (greedyRegisters R [] [] (wordGreedy (wordOracle which O) xs ps) []) 26 (q+greedyCalls xs) (c+greedyWork n xs) := by induction xs generalizing ps q c bits with | nil => simp [greedyTime,greedyWork,greedyCalls,wordGreedy,execution,machineStep,greedyProgram,greedyConfig,greedyRegisters] | cons b xs ih => have hn' : xs.length+ps.length+1=n := by simp only [List.length_cons] at hn; omega cases b with | false => simp only [greedyTime,greedyWork,greedyCalls,wordGreedy,Bool.false_and,Bool.false_eq_true,ite_false,Nat.zero_add] rw [List.length_cons,execution_add,greedy_false_body,ih] · congr 1 ; omega · simp only [List.length_cons]; omega | true => simp only [greedyTime,greedyWork,greedyCalls,wordGreedy,Bool.true_and,ite_true] rw [List.length_cons,execution_add,greedy_true_body _ _ _ _ _ hn',ih] · congr 1 <;> omega · simp only [List.length_cons]; omega end section variable {n : ℕ} def wordSet (n : ℕ) (l : List Bool) : Set (Fin n) := {i | l[i.val]?.getD false=true} lemma wordSet_zero_succ (m : ℕ) (ps : List Bool) : wordSet n (List.replicate (m+1) false++ps)=wordSet n (List.replicate m false++false::ps) := by congr 1 rw [List.replicate_add,List.replicate_one,List.append_assoc,List.singleton_append] lemma wordSet_bit (as ps : List Bool) (h : as.length simp theorem wordGreedy_basis (M : Matroid (Fin n)) (hE : M.E=Set.univ) (W : List Bool → Bool) (hW : ∀l,l.length=n → (W l=true ↔ M.Indep (wordSet n l))) (xs ps : List Bool) (hn : xs.length+ps.length=n) (hI : M.Indep (wordSet n (List.replicate xs.length false++ps))) : M.IsBasis (wordSet n (wordGreedy W xs ps)) (wordSet n (xs.reverse++ps)) := by induction xs generalizing ps with | nil => simpa [wordGreedy] using hI.isBasis_self | cons b xs ih => have hlen : xs.length+(b::ps).length=n := by simp only [List.length_cons] at *; omega have ha : xs.length simpa [wordGreedy,List.reverse_cons,List.append_assoc] using ih (false::ps) hlen hI' | true => cases hq : W (List.replicate xs.length false++true::ps) with | true => have hJ := (hW _ hqueryLen).mp hq simpa [wordGreedy,hq,List.reverse_cons,List.append_assoc] using ih (true::ps) hlen hJ | false => have hJ := ih (false::ps) (by simpa using hlen) hI' have han : ¬M.Indep (insert a (wordSet n (List.replicate xs.length false++false::ps))) := by rw [←hbit] intro h have := (hW _ hqueryLen).mpr h simp [hq] at this have hac : a ∈ M.closure (wordSet n (List.replicate xs.length false++false::ps)) := hI'.mem_closure_iff'.mpr ⟨by simp [hE],fun h => (han h).elim⟩ have hsub : wordSet n (List.replicate xs.length false++false::ps) ⊆ wordSet n (xs.reverse++false::ps) := by simpa using wordSet_zero_subset (n:=n) xs.reverse (false::ps) have hac' : a ∈ M.closure (wordSet n (wordGreedy W xs (false::ps))) := by rw [hJ.closure_eq_closure] exact M.closure_mono hsub hac have hB := hJ.indep.isBasis_of_subset_of_subset_closure (hJ.subset.trans (Set.subset_insert a _)) (Set.insert_subset hac' hJ.subset_closure) simpa [wordGreedy,hq,List.reverse_cons,List.append_assoc,hbit'] using hB end section variable {k n : ℕ} lemma incrementBits_length (ys : List Bool) : (incrementBits ys).length≤ys.length+1 := by induction ys with | nil => simp [incrementBits,leadingOnes,carryTail] | cons b ys ih => cases b <;> simp only [incrementBits,leadingOnes,carryTail,List.length_append,List.length_replicate, List.length_cons] at * <;> omega def popcountBits : List Bool → List Bool → List Bool | [],ys => ys | b::xs,ys => popcountBits xs (if b then incrementBits ys else ys) def popcountTime : List Bool → List Bool → ℕ | [],_ => 1 | b::xs,ys => 1+(if b then 4*leadingOnes ys+3 else 0)+popcountTime xs (if b then incrementBits ys else ys) lemma popcount_value (xs ys : List Bool) : binaryValue (popcountBits xs ys)=binaryValue ys+xs.count true := by induction xs generalizing ys with | nil => simp [popcountBits] | cons b xs ih => cases b <;> simp [popcountBits,ih,incrementBits_correct,_root_.Nat.add_comm,_root_.Nat.add_assoc] lemma popcountTime_bound (xs ys : List Bool) : popcountTime xs ys≤(4*(xs.length+ys.length)+4)*xs.length+1 := by induction xs generalizing ys with | nil => simp [popcountTime] | cons b xs ih => have hi := ih (if b then incrementBits ys else ys) have hl : (if b then incrementBits ys else ys).length≤ys.length+1 := by cases b <;> simp only [Bool.false_eq_true,ite_false,ite_true]; exacts [by omega,incrementBits_length ys] have hh := Nat.mul_le_mul_right xs.length (show 4*(xs.length+(if b then incrementBits ys else ys).length)+4≤ 4*(xs.length+ys.length+1)+4 by omega) have ho := leadingOnes_le ys cases b <;> simp only [popcountTime,List.length_cons,Bool.false_eq_true,ite_false,ite_true] at * <;> nlinarith def popcountConfig (R : Fin (k+8) → List Bool) (pc : Fin 7) (q c : ℕ) : MachineConfig k 6 := ⟨R,pc,none,q,c⟩ def popcountLabel (i : Fin 6) : Fin 7 := if i.val<5 then ⟨i.val+1,by omega⟩ else 0 def popcountProgram : Program k 6 := fun pc => if h0 : pc.val=0 then .pop 2 6 0 1 else if h1 : pc.val<6 then ((incrementProgram 0 3) ⟨pc.val-1,by omega⟩).relabel popcountLabel else .halt lemma popcount_increment (i : Fin 6) (hi : i≠5) : (popcountProgram : Program k 6) (popcountLabel i)=(incrementProgram 0 3 i).relabel popcountLabel := by have hh : i.val<5 := by have hb := i.isLt have hn : i.val≠5 := by intro h; exact hi (Fin.ext h) omega simp [popcountProgram,popcountLabel,hh,show i.val+1<6 by omega] lemma greedyRegisters_increment_in (R : Fin (k+8) → List Bool) (xs ys : List Bool) : pairRegisters (greedyRegisters R ys [] xs []) 0 3 ys []=greedyRegisters R ys [] xs [] := by funext i by_cases h0 : i=0 <;> by_cases h3 : i=3 <;> simp_all [pairRegisters,greedyRegisters] lemma greedyRegisters_increment_out (R : Fin (k+8) → List Bool) (xs ys : List Bool) : pairRegisters (greedyRegisters R ys [] xs []) 0 3 (incrementBits ys) []= greedyRegisters R (incrementBits ys) [] xs [] := by funext i by_cases h0 : i=0 <;> by_cases h3 : i=3 <;> simp_all [pairRegisters,greedyRegisters] lemma popcount_increment_run (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) (xs ys : List Bool) (q c : ℕ) (bits : ℕ → Bool) : execution popcountProgram O (popcountConfig (greedyRegisters R ys [] xs []) 1 q c) bits (4*leadingOnes ys+3)= popcountConfig (greedyRegisters R (incrementBits ys) [] xs []) 0 q (c+4*leadingOnes ys+3) := by have hi := (increment_block (k:=k) (0 : Fin (k+8)) 3 (by simp) O (greedyRegisters R ys [] xs []) ys q c bits).1 simp only [greedyRegisters_increment_in,greedyRegisters_increment_out] at hi have h := execution_relabel_before_halt (incrementProgram (k:=k) 0 3) popcountProgram popcountLabel 5 (by rfl) popcount_increment O (workConfig (greedyRegisters R ys [] xs []) 0 q c) bits (4*leadingOnes ys+3) (by rw [hi]; rfl) rw [hi] at h simpa [relabelConfig,workConfig,popcountConfig,popcountLabel] using h theorem popcount_run (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) (xs ys : List Bool) (q c : ℕ) (bits : ℕ → Bool) : execution popcountProgram O (popcountConfig (greedyRegisters R ys [] xs []) 0 q c) bits (popcountTime xs ys)= popcountConfig (greedyRegisters R (popcountBits xs ys) [] [] []) 6 q (c+popcountTime xs ys) := by induction xs generalizing ys c bits with | nil => simp [popcountTime,popcountBits,execution,machineStep,popcountProgram,popcountConfig,greedyRegisters] | cons b xs ih => have hp : execution popcountProgram O (popcountConfig (greedyRegisters R ys [] (b::xs) []) 0 q c) bits 1= popcountConfig (greedyRegisters R ys [] xs []) (if b then 1 else 0) q (c+1) := by cases b <;> simp [execution,machineStep,popcountProgram,popcountConfig,greedyRegisters,greedyRegisters_update2] cases b with | false => simp only [popcountTime,popcountBits,Bool.false_eq_true,ite_false,Nat.add_zero] rw [execution_add,hp] simp only [Bool.false_eq_true,ite_false] rw [ih] congr 1 ; omega | true => simp only [popcountTime,popcountBits,ite_true] rw [show 1+(4*leadingOnes ys+3)+popcountTime xs (incrementBits ys)= 1+((4*leadingOnes ys+3)+popcountTime xs (incrementBits ys)) by omega,execution_add,hp] simp only [ite_true] rw [execution_add,popcount_increment_run,ih] congr 1 ; omega end section open scoped BigOperators Classical variable {k n : ℕ} lemma count_ofFn (n : ℕ) (f : Fin n → Bool) : (List.ofFn f).count true=∑i,if f i then 1 else 0 := by induction n with | zero => simp | succ n ih => rw [List.ofFn_succ,Fin.sum_univ_succ] cases hf : f 0 <;> simp [ih,Nat.add_comm] lemma wordSet_card (xs : List Bool) (hn : xs.length=n) : Fintype.card (wordSet n xs)=xs.count true := by subst n let f : Fin xs.length → Bool := fun i => xs[i.val] have hf : List.ofFn f=xs := List.ofFn_getElem have hs : wordSet xs.length xs=wordSet xs.length (List.ofFn f) := congrArg (wordSet xs.length) hf.symm rw [hs,wordSet_ofFn,Fintype.card_subtype,Finset.card_filter] have hc := count_ofFn xs.length f rw [hf] at hc exact hc.symm lemma wordGreedy_rank (M : Matroid (Fin n)) (hE : M.E=Set.univ) (W : List Bool → Bool) (hW : ∀l,l.length=n → (W l=true ↔ M.Indep (wordSet n l))) (xs : List Bool) (hn : xs.length=n) : (wordGreedy W xs []).count true=(M.eRk (wordSet n xs.reverse)).toNat := by have h := wordGreedy_basis M hE W hW xs [] (by simpa using hn) (by simp [wordSet_zeros]) simp only [List.append_nil] at h have hh := h.encard_eq_eRk rw [Set.encard_eq_coe_toFinset_card] at hh have hc : (wordSet n (wordGreedy W xs [])).toFinset.card=(wordGreedy W xs []).count true := by rw [Set.toFinset_card] exact wordSet_card _ (by simpa [wordGreedy_length] using hn) rw [hc] at hh simpa using congrArg ENat.toNat hh def rankProgram (which : Bool) : Program k 32 := concatProgram (greedyProgram which) popcountProgram def rankConfig (R : Fin (k+8) → List Bool) (pc : Fin 33) (q c : ℕ) : MachineConfig k 32 := ⟨R,pc,none,q,c⟩ def rankBits (which : Bool) (O : IndependenceOracle n) (xs : List Bool) : List Bool := popcountBits (wordGreedy (wordOracle which O) xs []) [] def rankTime (which : Bool) (O : IndependenceOracle n) (xs : List Bool) : ℕ := greedyTime n xs+popcountTime (wordGreedy (wordOracle which O) xs []) [] def rankWork (which : Bool) (O : IndependenceOracle n) (xs : List Bool) : ℕ := greedyWork n xs+popcountTime (wordGreedy (wordOracle which O) xs []) [] lemma rankTime_bound (which : Bool) (O : IndependenceOracle n) (xs : List Bool) (hn : xs.length=n) : rankTime which O xs≤(10*n+9)*n+2 := by have hg := greedyTime_bound n xs have hp := popcountTime_bound (wordGreedy (wordOracle which O) xs []) [] simp only [wordGreedy_length,List.length_nil,Nat.add_zero,hn] at * unfold rankTime nlinarith lemma rankWork_bound (which : Bool) (O : IndependenceOracle n) (xs : List Bool) (hn : xs.length=n) : rankWork which O xs≤(12*n+9)*n+2 := by have hg := greedyWork_bound n xs have hp := popcountTime_bound (wordGreedy (wordOracle which O) xs []) [] simp only [wordGreedy_length,List.length_nil,Nat.add_zero,hn] at * unfold rankWork nlinarith lemma rank_run (which : Bool) (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) (xs : List Bool) (hn : xs.length=n) (q c : ℕ) (bits : ℕ → Bool) : execution (rankProgram which) O (rankConfig (greedyRegisters R xs (List.replicate n false) [] []) 0 q c) bits (rankTime which O xs)= rankConfig (greedyRegisters R (rankBits which O xs) [] [] []) 32 (q+greedyCalls xs) (c+rankWork which O xs) := by have hg := greedy_machine_run which O R xs [] (by simpa using hn) q c bits have hp := popcount_run O R (wordGreedy (wordOracle which O) xs []) [] (q+greedyCalls xs) (c+greedyWork n xs) (fun i => bits (greedyTime n xs+i)) have h := concat_run (greedyProgram (k:=k) which) popcountProgram (by rfl) O (greedyConfig (greedyRegisters R xs (List.replicate xs.length false) [] []) 0 q c) bits (greedyTime n xs) (popcountTime (wordGreedy (wordOracle which O) xs []) []) (by rw [hg]; rfl) (by rw [hg]; rfl) rw [hg] at h have hre : restartControl (greedyConfig (greedyRegisters R [] [] (wordGreedy (wordOracle which O) xs []) []) 26 (q+greedyCalls xs) (c+greedyWork n xs)) (0 : Fin 7)= popcountConfig (greedyRegisters R [] [] (wordGreedy (wordOracle which O) xs []) []) 0 (q+greedyCalls xs) (c+greedyWork n xs) := rfl rw [hre,hp] at h simpa [rankProgram,rankConfig,rankTime,rankWork,rankBits,relabelConfig,greedyConfig,popcountConfig, firstLabel,secondLabel,hn,Nat.add_assoc] using h theorem matroid_rank_machine (M₁ M₂ : Matroid (Fin n)) (O : IndependenceOracle n) (hO : ExactOracles M₁ M₂ O) (hE₁ : M₁.E=Set.univ) (hE₂ : M₂.E=Set.univ) (which : Bool) (S : Fin n → Bool) (R : Fin (k+8) → List Bool) (q c : ℕ) (bits : ℕ → Bool) : let xs := (List.ofFn S).reverse let z := rankBits which O xs let t := rankTime which O xs let w := rankWork which O xs binaryValue z=((if which then M₂ else M₁).eRk {i | S i=true}).toNat ∧ t≤(10*n+9)*n+2 ∧ w≤(12*n+9)*n+2 ∧ greedyCalls xs≤n ∧ execution (rankProgram which) O (rankConfig (greedyRegisters R xs (List.replicate n false) [] []) 0 q c) bits t= rankConfig (greedyRegisters R z [] [] []) 32 (q+greedyCalls xs) (c+w) := by have hn : (List.ofFn S).reverse.length=n := by simp refine ⟨?_,rankTime_bound which O _ hn,rankWork_bound which O _ hn,?_,rank_run which O R _ hn q c bits⟩ · simp only [rankBits,popcount_value,binaryValue,Nat.zero_add] have hr := wordGreedy_rank (if which then M₂ else M₁) (by cases which <;> assumption) (wordOracle which O) (fun l _ => hO which (fun i => l[i.val]?.getD false)) (List.ofFn S).reverse hn simpa only [List.reverse_reverse,wordSet_ofFn] using hr · simpa using greedyCalls_bound (List.ofFn S).reverse end section variable {k n : ℕ} def compareBits : Bool → List Bool → List Bool → Bool | b,[],[] => b | b,[],y::ys => compareBits (if y then true else b) [] ys | b,x::xs,[] => compareBits (if x then false else b) xs [] | b,x::xs,y::ys => compareBits (if x=y then b else y) xs ys lemma compareBits_correct (b : Bool) (xs ys : List Bool) : compareBits b xs ys=true ↔ binaryValue xs induction ys generalizing b with | nil => simp [compareBits,binaryValue] | cons y ys ih => rw [compareBits,ih] cases b <;> cases y <;> simp [binaryValue] <;> omega | cons x xs ih => cases ys with | nil => rw [compareBits,ih] cases b <;> cases x <;> simp [binaryValue] | cons y ys => rw [compareBits,ih] cases b <;> cases x <;> cases y <;> simp [binaryValue] <;> omega lemma compareBits_lt (xs ys : List Bool) : compareBits false xs ys=true ↔ binaryValue xs match pc.val with | 0 => .pop a 1 2 3 | 1 => .pop b 8 0 4 | 2 => .pop b 0 0 4 | 3 => .pop b 0 0 0 | 4 => .pop a 5 6 7 | 5 => .pop b 9 4 4 | 6 => .pop b 4 4 4 | 7 => .pop b 0 0 4 | _ => .halt theorem comparison_run (a b : Fin (k+8)) (hab : a≠b) (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) (xs ys : List Bool) (lt : Bool) (q c : ℕ) (bits : ℕ → Bool) : execution (compareProgram a b) O (compareConfig (pairRegisters R a b xs ys) (if lt then 4 else 0) q c) bits (2*max xs.length ys.length+2)= compareConfig (pairRegisters R a b [] []) (if compareBits lt xs ys then 9 else 8) q (c+(2*max xs.length ys.length+2)) := by induction xs generalizing lt ys c bits with | nil => induction ys generalizing lt c bits with | nil => cases lt <;> simp [execution,machineStep,compareProgram,compareConfig,pairRegisters_a _ _ _ hab,pairRegisters_b,compareBits] | cons y ys ih => have hstep : execution (compareProgram a b) O (compareConfig (pairRegisters R a b [] (y::ys)) (if lt then 4 else 0) q c) bits 2= compareConfig (pairRegisters R a b [] ys) (if (if y then true else lt) then 4 else 0) q (c+2) := by cases lt <;> cases y <;> simp [execution,machineStep,compareProgram,compareConfig, pairRegisters_a _ _ _ hab,pairRegisters_b,pairRegisters_update_b] simp only [List.length_nil,List.length_cons,Nat.zero_max] rw [show 2*(ys.length+1)+2=2+(2*ys.length+2) by omega,execution_add,hstep] simpa [compareBits,Nat.add_assoc] using ih (if y then true else lt) (c+2) (fun i => bits (2+i)) | cons x xs ih => cases ys with | nil => have hstep : execution (compareProgram a b) O (compareConfig (pairRegisters R a b (x::xs) []) (if lt then 4 else 0) q c) bits 2= compareConfig (pairRegisters R a b xs []) (if (if x then false else lt) then 4 else 0) q (c+2) := by cases lt <;> cases x <;> simp [execution,machineStep,compareProgram,compareConfig, pairRegisters_a _ _ _ hab,pairRegisters_b,pairRegisters_update_a _ _ _ hab] simp only [List.length_nil,List.length_cons,Nat.max_zero] rw [show 2*(xs.length+1)+2=2+(2*xs.length+2) by omega,execution_add,hstep] simpa [compareBits,Nat.add_assoc] using ih [] (if x then false else lt) (c+2) (fun i => bits (2+i)) | cons y ys => have hstep : execution (compareProgram a b) O (compareConfig (pairRegisters R a b (x::xs) (y::ys)) (if lt then 4 else 0) q c) bits 2= compareConfig (pairRegisters R a b xs ys) (if (if x=y then lt else y) then 4 else 0) q (c+2) := by cases lt <;> cases x <;> cases y <;> simp [execution,machineStep,compareProgram,compareConfig, pairRegisters_a _ _ _ hab,pairRegisters_b,pairRegisters_update_a _ _ _ hab,pairRegisters_update_b] simp only [List.length_cons,max_add_add_right] rw [show 2*(max xs.length ys.length+1)+2=2+(2*max xs.length ys.length+2) by omega,execution_add,hstep] simpa [compareBits,Nat.add_assoc] using ih ys (if x=y then lt else y) (c+2) (fun i => bits (2+i)) theorem comparison_block (a b : Fin (k+8)) (hab : a≠b) (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) (xs ys : List Bool) (q c : ℕ) (bits : ℕ → Bool) : let t := 2*max xs.length ys.length+2 execution (compareProgram a b) O (compareConfig (pairRegisters R a b xs ys) 0 q c) bits t= compareConfig (pairRegisters R a b [] []) (if binaryValue xs [] | x::xs,[] => sumDigit x false c :: subDigits (subBorrow x false c) xs [] | [],y::ys => sumDigit false y c :: subDigits (subBorrow false y c) [] ys | x::xs,y::ys => sumDigit x y c :: subDigits (subBorrow x y c) xs ys termination_by xs.length+ys.length def subCost (c : Bool) (xs ys : List Bool) : ℕ := match xs,ys with | [],[] => 2 | x::xs,[] => 3+subCost (subBorrow x false c) xs [] | [],y::ys => 3+subCost (subBorrow false y c) [] ys | x::xs,y::ys => 3+subCost (subBorrow x y c) xs ys termination_by xs.length+ys.length lemma subDigits_value (c : Bool) (xs ys : List Bool) (h : binaryValue ys+(if c then 1 else 0)≤binaryValue xs) : binaryValue (subDigits c xs ys)+binaryValue ys+(if c then 1 else 0)=binaryValue xs := by induction xs generalizing ys c with | nil => induction ys generalizing c with | nil => cases c <;> simp_all [subDigits,binaryValue] | cons y ys ih => cases y <;> cases c <;> simp_all [binaryValue,subDigits,subBorrow,sumDigit] | cons x xs ih => cases ys with | nil => have ht : binaryValue []+(if subBorrow x false c then 1 else 0)≤binaryValue xs := by cases x <;> cases c <;> simp_all [binaryValue,subBorrow] ; omega have hi := ih (subBorrow x false c) [] ht simp only [subDigits,binaryValue] cases x <;> cases c <;> simp [subBorrow,sumDigit,binaryValue] at hi h ⊢ <;> omega | cons y ys => have ht : binaryValue ys+(if subBorrow x y c then 1 else 0)≤binaryValue xs := by cases x <;> cases y <;> cases c <;> simp_all [binaryValue,subBorrow] <;> omega have hi := ih (subBorrow x y c) ys ht simp only [subDigits,binaryValue] cases x <;> cases y <;> cases c <;> simp [subBorrow,sumDigit,binaryValue] at hi h ⊢ <;> omega lemma subDigits_length_cost (c : Bool) (xs ys : List Bool) : (subDigits c xs ys).length≤xs.length+ys.length+1 ∧ subCost c xs ys≤3*(xs.length+ys.length)+3 := by induction xs generalizing ys c with | nil => induction ys generalizing c with | nil => cases c <;> simp [subDigits,subCost] | cons y ys ih => have hi := ih (subBorrow false y c) simp only [subDigits,subCost,List.length_cons,List.length_nil] at * constructor <;> omega | cons x xs ih => cases ys with | nil => have hi := ih (subBorrow x false c) [] simp only [subDigits,subCost,List.length_cons,List.length_nil] at * constructor <;> omega | cons y ys => have hi := ih (subBorrow x y c) ys simp only [subDigits,subCost,List.length_cons] at * constructor <;> omega def subConfig (R : Fin (k+8) → List Bool) (pc : Fin 17) (q c : ℕ) : MachineConfig k 16 := ⟨R,pc,none,q,c⟩ def subProgram (a b d : Fin (k+8)) : Program k 16 := fun pc => match pc.val with | 0 => .pop a 2 3 4 | 1 => .pop a 5 6 7 | 2 => .pop b 12 8 11 | 3 => .pop b 8 8 11 | 4 => .pop b 9 9 8 | 5 => .pop b 12 11 10 | 6 => .pop b 11 11 10 | 7 => .pop b 8 8 11 | 8 => .push d false 0 | 9 => .push d true 0 | 10 => .push d false 1 | 11 => .push d true 1 | 12 => .pop d 16 14 15 | 13 => .halt | 14 => .push a false 12 | 15 => .push a true 12 | _ => .halt lemma sub_build (a b d : Fin (k+8)) (hab : a≠b) (had : a≠d) (hbd : b≠d) (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) (xs ys zs : List Bool) (carry : Bool) (q c : ℕ) (bits : ℕ → Bool) : execution (subProgram a b d) O (subConfig (tripleRegisters R a b d xs ys zs) (if carry then 1 else 0) q c) bits (subCost carry xs ys)=subConfig (tripleRegisters R a b d [] [] ((subDigits carry xs ys).reverse++zs)) 12 q (c+subCost carry xs ys) := by induction xs generalizing ys zs carry c bits with | nil => induction ys generalizing zs carry c bits with | nil => cases carry <;> simp [subCost,subDigits,execution,machineStep,subProgram,subConfig, tripleRegisters_a _ _ _ _ hab had,tripleRegisters_b _ _ _ _ hbd,] | cons y ys ih => have ht : execution (subProgram a b d) O (subConfig (tripleRegisters R a b d [] (y::ys) zs) (if carry then 1 else 0) q c) bits 3= subConfig (tripleRegisters R a b d [] ys (sumDigit false y carry::zs)) (if subBorrow false y carry then 1 else 0) q (c+3) := by cases y <;> cases carry <;> simp [execution,machineStep,subProgram,subConfig,sumDigit,subBorrow, tripleRegisters_a _ _ _ _ hab had,tripleRegisters_b _ _ _ _ hbd,tripleRegisters_d, tripleRegisters_update_b _ _ _ _ hbd,tripleRegisters_update_d] rw [subCost,execution_add,ht,ih] simp only [subDigits,List.reverse_cons,List.append_assoc,List.singleton_append] congr 1 ; omega | cons x xs ih => cases ys with | nil => have ht : execution (subProgram a b d) O (subConfig (tripleRegisters R a b d (x::xs) [] zs) (if carry then 1 else 0) q c) bits 3= subConfig (tripleRegisters R a b d xs [] (sumDigit x false carry::zs)) (if subBorrow x false carry then 1 else 0) q (c+3) := by cases x <;> cases carry <;> simp [execution,machineStep,subProgram,subConfig,sumDigit,subBorrow, tripleRegisters_a _ _ _ _ hab had,tripleRegisters_b _ _ _ _ hbd,tripleRegisters_d, tripleRegisters_update_a _ _ _ _ hab had,tripleRegisters_update_d] rw [subCost,execution_add,ht,ih] simp only [subDigits,List.reverse_cons,List.append_assoc,List.singleton_append] congr 1 ; omega | cons y ys => have ht : execution (subProgram a b d) O (subConfig (tripleRegisters R a b d (x::xs) (y::ys) zs) (if carry then 1 else 0) q c) bits 3= subConfig (tripleRegisters R a b d xs ys (sumDigit x y carry::zs)) (if subBorrow x y carry then 1 else 0) q (c+3) := by cases x <;> cases y <;> cases carry <;> simp [execution,machineStep,subProgram,subConfig,sumDigit,subBorrow, tripleRegisters_a _ _ _ _ hab had,tripleRegisters_b _ _ _ _ hbd,tripleRegisters_d, tripleRegisters_update_a _ _ _ _ hab had,tripleRegisters_update_b _ _ _ _ hbd, tripleRegisters_update_d] rw [subCost,execution_add,ht,ih] simp only [subDigits,List.reverse_cons,List.append_assoc,List.singleton_append] congr 1 ; omega lemma sub_restore (a b d : Fin (k+8)) (hab : a≠b) (had : a≠d) (_ : b≠d) (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) (xs ys zs : List Bool) (q c : ℕ) (bits : ℕ → Bool) : execution (subProgram a b d) O (subConfig (tripleRegisters R a b d xs ys zs) 12 q c) bits (2*zs.length+1)=subConfig (tripleRegisters R a b d (zs.reverse++xs) ys []) 16 q (c+2*zs.length+1) := by induction zs generalizing xs c bits with | nil => simp [execution,machineStep,subProgram,subConfig,tripleRegisters_d] | cons z zs ih => have ht : execution (subProgram a b d) O (subConfig (tripleRegisters R a b d xs ys (z::zs)) 12 q c) bits 2= subConfig (tripleRegisters R a b d (z::xs) ys zs) 12 q (c+2) := by cases z <;> simp [execution,machineStep,subProgram,subConfig,tripleRegisters_a _ _ _ _ hab had, tripleRegisters_d,tripleRegisters_update_a _ _ _ _ hab had,tripleRegisters_update_d] rw [List.length_cons,show 2*(zs.length+1)+1=2+(2*zs.length+1) by omega,execution_add,ht,ih] simp only [List.reverse_cons,List.append_assoc,List.singleton_append] congr 1 ; omega theorem subtraction_block (a b d : Fin (k+8)) (hab : a≠b) (had : a≠d) (hbd : b≠d) (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) (xs ys : List Bool) (hxy : binaryValue ys≤binaryValue xs) (q c : ℕ) (bits : ℕ → Bool) : let z := subDigits false xs ys let t := subCost false xs ys+2*z.length+1 binaryValue z=binaryValue xs-binaryValue ys ∧ t≤5*(xs.length+ys.length)+6 ∧ execution (subProgram a b d) O (subConfig (tripleRegisters R a b d xs ys []) 0 q c) bits t= subConfig (tripleRegisters R a b d z [] []) 16 q (c+t) := by dsimp only refine ⟨?_,?_,?_⟩ · have h := subDigits_value false xs ys (by simpa using hxy) simp only [Bool.false_eq_true,ite_false,Nat.add_zero] at h omega · have h := subDigits_length_cost false xs ys omega · rw [show subCost false xs ys+2*(subDigits false xs ys).length+1= subCost false xs ys+(2*(subDigits false xs ys).length+1) by omega,execution_add] rw [show (0 : Fin 17)=(if false then 1 else 0) by rfl,sub_build a b d hab had hbd] simp only [List.append_nil] rw [←List.length_reverse (as:=subDigits false xs ys),sub_restore a b d hab had hbd] simp only [List.reverse_reverse,List.length_reverse,List.append_nil] congr 1 ; omega end section variable {k s t n : ℕ} lemma execution_relabel_before_any_halt (P : Program k s) (Q : Program k t) (e : Fin (s+1) → Fin (t+1)) (h : ∀ i,P i≠.halt → Q (e i)=(P i).relabel e) (O : IndependenceOracle n) (c : MachineConfig k s) (bits : ℕ → Bool) (u : ℕ) (hu : (execution P O c bits u).output=none) : execution Q O (relabelConfig e c) bits u=relabelConfig e (execution P O c bits u) := by induction u with | zero => rfl | succ u ih => have hn := machineStep_none_pre P O (bits u) (execution P O c bits u) hu have hh := machineStep_none_not_halt P O (bits u) (execution P O c bits u) hu simp only [execution,ih hn] exact machineStep_relabel P Q e O _ _ (h _ hh) lemma execution_of_output (P : Program k s) (O : IndependenceOracle n) (c : MachineConfig k s) (bits : ℕ → Bool) (u : ℕ) (h : c.output.isSome) : execution P O c bits u=c := by induction u with | zero => rfl | succ u ih => simp [execution,ih,machineStep,h] lemma execution_extend_output (P : Program k s) (O : IndependenceOracle n) (c : MachineConfig k s) (bits : ℕ → Bool) (u B : ℕ) (hu : u≤B) (h : (execution P O c bits u).output.isSome) : execution P O c bits B=execution P O c bits u := by rw [show B=u+(B-u) by omega,execution_add] exact execution_of_output P O _ _ _ h end section variable {k n : ℕ} @[simp] lemma workReg_ne05 : (0 : Fin (k+8))≠5 := workReg_ne (a:=0) (b:=5) (by omega) (by omega) (by omega) @[simp] lemma workReg_ne06 : (0 : Fin (k+8))≠6 := workReg_ne (a:=0) (b:=6) (by omega) (by omega) (by omega) @[simp] lemma workReg_ne15 : (1 : Fin (k+8))≠5 := workReg_ne (a:=1) (b:=5) (by omega) (by omega) (by omega) @[simp] lemma workReg_ne16 : (1 : Fin (k+8))≠6 := workReg_ne (a:=1) (b:=6) (by omega) (by omega) (by omega) @[simp] lemma workReg_ne25 : (2 : Fin (k+8))≠5 := workReg_ne (a:=2) (b:=5) (by omega) (by omega) (by omega) @[simp] lemma workReg_ne26 : (2 : Fin (k+8))≠6 := workReg_ne (a:=2) (b:=6) (by omega) (by omega) (by omega) @[simp] lemma workReg_ne35 : (3 : Fin (k+8))≠5 := workReg_ne (a:=3) (b:=5) (by omega) (by omega) (by omega) @[simp] lemma workReg_ne36 : (3 : Fin (k+8))≠6 := workReg_ne (a:=3) (b:=6) (by omega) (by omega) (by omega) @[simp] lemma workReg_ne45 : (4 : Fin (k+8))≠5 := workReg_ne (a:=4) (b:=5) (by omega) (by omega) (by omega) @[simp] lemma workReg_ne46 : (4 : Fin (k+8))≠6 := workReg_ne (a:=4) (b:=6) (by omega) (by omega) (by omega) @[simp] lemma workReg_ne50 : (5 : Fin (k+8))≠0 := workReg_ne (a:=5) (b:=0) (by omega) (by omega) (by omega) @[simp] lemma workReg_ne51 : (5 : Fin (k+8))≠1 := workReg_ne (a:=5) (b:=1) (by omega) (by omega) (by omega) @[simp] lemma workReg_ne52 : (5 : Fin (k+8))≠2 := workReg_ne (a:=5) (b:=2) (by omega) (by omega) (by omega) @[simp] lemma workReg_ne53 : (5 : Fin (k+8))≠3 := workReg_ne (a:=5) (b:=3) (by omega) (by omega) (by omega) @[simp] lemma workReg_ne54 : (5 : Fin (k+8))≠4 := workReg_ne (a:=5) (b:=4) (by omega) (by omega) (by omega) @[simp] lemma workReg_ne56 : (5 : Fin (k+8))≠6 := workReg_ne (a:=5) (b:=6) (by omega) (by omega) (by omega) @[simp] lemma workReg_ne60 : (6 : Fin (k+8))≠0 := workReg_ne (a:=6) (b:=0) (by omega) (by omega) (by omega) @[simp] lemma workReg_ne61 : (6 : Fin (k+8))≠1 := workReg_ne (a:=6) (b:=1) (by omega) (by omega) (by omega) @[simp] lemma workReg_ne62 : (6 : Fin (k+8))≠2 := workReg_ne (a:=6) (b:=2) (by omega) (by omega) (by omega) @[simp] lemma workReg_ne63 : (6 : Fin (k+8))≠3 := workReg_ne (a:=6) (b:=3) (by omega) (by omega) (by omega) @[simp] lemma workReg_ne64 : (6 : Fin (k+8))≠4 := workReg_ne (a:=6) (b:=4) (by omega) (by omega) (by omega) @[simp] lemma workReg_ne65 : (6 : Fin (k+8))≠5 := workReg_ne (a:=6) (b:=5) (by omega) (by omega) (by omega) def divRegisters (R : Fin (k+8) → List Bool) (xs ys zs ws as bs : List Bool) : Fin (k+8) → List Bool := fun i => if i=0 then xs else if i=1 then ys else if i=2 then zs else if i=3 then ws else if i=4 then [] else if i=5 then as else if i=6 then bs else R i lemma divRegisters_copyR_in (R : Fin (k+8) → List Bool) (xs ys zs ws as bs : List Bool) : tripleRegisters (divRegisters R xs ys zs ws as bs) 2 4 5 zs [] as=divRegisters R xs ys zs ws as bs := by funext i by_cases h0 : i=0 <;> by_cases h1 : i=1 <;> by_cases h2 : i=2 <;> by_cases h3 : i=3 <;> by_cases h4 : i=4 <;> by_cases h5 : i=5 <;> by_cases h6 : i=6 <;> simp_all [divRegisters,tripleRegisters,pairRegisters] lemma divRegisters_copyR_out (R : Fin (k+8) → List Bool) (xs ys zs ws bs : List Bool) : tripleRegisters (divRegisters R xs ys zs ws [] bs) 2 4 5 zs [] zs=divRegisters R xs ys zs ws zs bs := by funext i by_cases h0 : i=0 <;> by_cases h1 : i=1 <;> by_cases h2 : i=2 <;> by_cases h3 : i=3 <;> by_cases h4 : i=4 <;> by_cases h5 : i=5 <;> by_cases h6 : i=6 <;> simp_all [divRegisters,tripleRegisters,pairRegisters] lemma divRegisters_copyD_in (R : Fin (k+8) → List Bool) (xs ys zs ws as bs : List Bool) : tripleRegisters (divRegisters R xs ys zs ws as bs) 1 4 6 ys [] bs=divRegisters R xs ys zs ws as bs := by funext i by_cases h0 : i=0 <;> by_cases h1 : i=1 <;> by_cases h2 : i=2 <;> by_cases h3 : i=3 <;> by_cases h4 : i=4 <;> by_cases h5 : i=5 <;> by_cases h6 : i=6 <;> simp_all [divRegisters,tripleRegisters,pairRegisters] lemma divRegisters_copyD_out (R : Fin (k+8) → List Bool) (xs ys zs ws as : List Bool) : tripleRegisters (divRegisters R xs ys zs ws as []) 1 4 6 ys [] ys=divRegisters R xs ys zs ws as ys := by funext i by_cases h0 : i=0 <;> by_cases h1 : i=1 <;> by_cases h2 : i=2 <;> by_cases h3 : i=3 <;> by_cases h4 : i=4 <;> by_cases h5 : i=5 <;> by_cases h6 : i=6 <;> simp_all [divRegisters,tripleRegisters,pairRegisters] lemma divRegisters_compare_in (R : Fin (k+8) → List Bool) (xs ys zs ws as bs : List Bool) : pairRegisters (divRegisters R xs ys zs ws as bs) 5 6 as bs=divRegisters R xs ys zs ws as bs := by funext i by_cases h0 : i=0 <;> by_cases h1 : i=1 <;> by_cases h2 : i=2 <;> by_cases h3 : i=3 <;> by_cases h4 : i=4 <;> by_cases h5 : i=5 <;> by_cases h6 : i=6 <;> simp_all [divRegisters,pairRegisters] lemma divRegisters_compare_out (R : Fin (k+8) → List Bool) (xs ys zs ws as bs : List Bool) : pairRegisters (divRegisters R xs ys zs ws as bs) 5 6 [] []=divRegisters R xs ys zs ws [] [] := by funext i by_cases h0 : i=0 <;> by_cases h1 : i=1 <;> by_cases h2 : i=2 <;> by_cases h3 : i=3 <;> by_cases h4 : i=4 <;> by_cases h5 : i=5 <;> by_cases h6 : i=6 <;> simp_all [divRegisters,pairRegisters] lemma divRegisters_copyS_in (R : Fin (k+8) → List Bool) (xs ys zs ws as bs : List Bool) : tripleRegisters (divRegisters R xs ys zs ws as bs) 1 4 5 ys [] as=divRegisters R xs ys zs ws as bs := by funext i by_cases h0 : i=0 <;> by_cases h1 : i=1 <;> by_cases h2 : i=2 <;> by_cases h3 : i=3 <;> by_cases h4 : i=4 <;> by_cases h5 : i=5 <;> by_cases h6 : i=6 <;> simp_all [divRegisters,tripleRegisters,pairRegisters] lemma divRegisters_copyS_out (R : Fin (k+8) → List Bool) (xs ys zs ws bs : List Bool) : tripleRegisters (divRegisters R xs ys zs ws [] bs) 1 4 5 ys [] ys=divRegisters R xs ys zs ws ys bs := by funext i by_cases h0 : i=0 <;> by_cases h1 : i=1 <;> by_cases h2 : i=2 <;> by_cases h3 : i=3 <;> by_cases h4 : i=4 <;> by_cases h5 : i=5 <;> by_cases h6 : i=6 <;> simp_all [divRegisters,tripleRegisters,pairRegisters] lemma divRegisters_sub_in (R : Fin (k+8) → List Bool) (xs ys zs ws as bs : List Bool) : tripleRegisters (divRegisters R xs ys zs ws as bs) 2 5 4 zs as []=divRegisters R xs ys zs ws as bs := by funext i by_cases h0 : i=0 <;> by_cases h1 : i=1 <;> by_cases h2 : i=2 <;> by_cases h3 : i=3 <;> by_cases h4 : i=4 <;> by_cases h5 : i=5 <;> by_cases h6 : i=6 <;> simp_all [divRegisters,tripleRegisters,pairRegisters] lemma divRegisters_sub_out (R : Fin (k+8) → List Bool) (xs ys zs ws as bs : List Bool) (us : List Bool) : tripleRegisters (divRegisters R xs ys zs ws as bs) 2 5 4 us [] []=divRegisters R xs ys us ws [] bs := by funext i by_cases h0 : i=0 <;> by_cases h1 : i=1 <;> by_cases h2 : i=2 <;> by_cases h3 : i=3 <;> by_cases h4 : i=4 <;> by_cases h5 : i=5 <;> by_cases h6 : i=6 <;> simp_all [divRegisters,tripleRegisters,pairRegisters] lemma divRegisters_update0 (R : Fin (k+8) → List Bool) (xs ys zs ws as bs : List Bool) (us : List Bool) : Function.update (divRegisters R xs ys zs ws as bs) 0 us=divRegisters R us ys zs ws as bs := by funext i by_cases h0 : i=0 <;> by_cases h1 : i=1 <;> by_cases h2 : i=2 <;> by_cases h3 : i=3 <;> by_cases h4 : i=4 <;> by_cases h5 : i=5 <;> by_cases h6 : i=6 <;> simp_all [divRegisters,] lemma divRegisters_update2 (R : Fin (k+8) → List Bool) (xs ys zs ws as bs : List Bool) (us : List Bool) : Function.update (divRegisters R xs ys zs ws as bs) 2 us=divRegisters R xs ys us ws as bs := by funext i by_cases h0 : i=0 <;> by_cases h1 : i=1 <;> by_cases h2 : i=2 <;> by_cases h3 : i=3 <;> by_cases h4 : i=4 <;> by_cases h5 : i=5 <;> by_cases h6 : i=6 <;> simp_all [divRegisters,] lemma divRegisters_update3 (R : Fin (k+8) → List Bool) (xs ys zs ws as bs : List Bool) (us : List Bool) : Function.update (divRegisters R xs ys zs ws as bs) 3 us=divRegisters R xs ys zs us as bs := by funext i by_cases h0 : i=0 <;> by_cases h1 : i=1 <;> by_cases h2 : i=2 <;> by_cases h3 : i=3 <;> by_cases h4 : i=4 <;> by_cases h5 : i=5 <;> by_cases h6 : i=6 <;> simp_all [divRegisters,] def divCopies : Program k 16 := concatProgram (copyProgram 2 4 5) (copyProgram 1 4 6) def divCheck : Program k 25 := concatProgram divCopies (compareProgram 5 6) def divSubtract : Program k 24 := concatProgram (copyProgram 1 4 5) (subProgram 2 5 4) def divCopiesConfig (R : Fin (k+8) → List Bool) (pc : Fin 17) (q c : ℕ) : MachineConfig k 16 := ⟨R,pc,none,q,c⟩ def divCheckConfig (R : Fin (k+8) → List Bool) (pc : Fin 26) (q c : ℕ) : MachineConfig k 25 := ⟨R,pc,none,q,c⟩ def divSubtractConfig (R : Fin (k+8) → List Bool) (pc : Fin 25) (q c : ℕ) : MachineConfig k 24 := ⟨R,pc,none,q,c⟩ lemma divCopies_exit : (divCopies : Program k 16) (lastLabel 16)=.halt := by simp [divCopies,concatProgram,lastLabel,copyProgram,Instruction.relabel] lemma divSubtract_exit : (divSubtract : Program k 24) (lastLabel 24)=.halt := by simp [divSubtract,concatProgram,lastLabel,subProgram,Instruction.relabel] lemma divCopies_run (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) (xs ys zs ws : List Bool) (q c : ℕ) (bits : ℕ → Bool) : execution divCopies O (divCopiesConfig (divRegisters R xs ys zs ws [] []) 0 q c) bits ((5*zs.length+2)+(5*ys.length+2))= divCopiesConfig (divRegisters R xs ys zs ws zs ys) 16 q (c+((5*zs.length+2)+(5*ys.length+2))) := by have hc := copy_block (k:=k) (2 : Fin (k+8)) 4 5 (by simp) (by simp) (by simp) O (divRegisters R xs ys zs ws [] []) zs [] q c bits simp only [List.append_nil,divRegisters_copyR_in,divRegisters_copyR_out] at hc have hd := copy_block (k:=k) (1 : Fin (k+8)) 4 6 (by simp) (by simp) (by simp) O (divRegisters R xs ys zs ws zs []) ys [] q (c+(5*zs.length+2)) (fun i => bits (5*zs.length+2+i)) simp only [List.append_nil,divRegisters_copyD_in,divRegisters_copyD_out] at hd have hh := concat_run (copyProgram (k:=k) 2 4 5) (copyProgram 1 4 6) (by rfl) O (copyConfig (divRegisters R xs ys zs ws [] []) 0 q c) bits (5*zs.length+2) (5*ys.length+2) (by rw [hc]; rfl) (by rw [hc]; rfl) rw [hc] at hh have hre : restartControl (copyConfig (divRegisters R xs ys zs ws zs []) 8 q (c+5*zs.length+2)) (0 : Fin 9)=copyConfig (divRegisters R xs ys zs ws zs []) 0 q (c+(5*zs.length+2)) := by simp [restartControl,copyConfig,Nat.add_assoc] rw [hre,hd] at hh simpa [divCopies,divCopiesConfig,copyConfig,relabelConfig,firstLabel,secondLabel,Nat.add_assoc] using hh def divCheckCost (ys zs : List Bool) : ℕ := (5*zs.length+2)+(5*ys.length+2)+(2*max zs.length ys.length+2) lemma divCheck_run (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) (xs ys zs ws : List Bool) (q c : ℕ) (bits : ℕ → Bool) : execution divCheck O (divCheckConfig (divRegisters R xs ys zs ws [] []) 0 q c) bits (divCheckCost ys zs)= divCheckConfig (divRegisters R xs ys zs ws [] []) (if binaryValue zs bits ((5*zs.length+2)+(5*ys.length+2)+i)) dsimp only at hd simp only [divRegisters_compare_in,divRegisters_compare_out] at hd have hh := concat_run (divCopies : Program k 16) (compareProgram 5 6) divCopies_exit O (divCopiesConfig (divRegisters R xs ys zs ws [] []) 0 q c) bits ((5*zs.length+2)+(5*ys.length+2)) (2*max zs.length ys.length+2) (by rw [hc]; rfl) (by rw [hc]; rfl) rw [hc] at hh have hre : restartControl (divCopiesConfig (divRegisters R xs ys zs ws zs ys) 16 q (c+((5*zs.length+2)+(5*ys.length+2)))) (0 : Fin 10)=compareConfig (divRegisters R xs ys zs ws zs ys) 0 q (c+((5*zs.length+2)+(5*ys.length+2))) := rfl rw [hre,hd] at hh split_ifs at hh ⊢ <;> simpa [divCheck,divCheckCost,divCopiesConfig,divCheckConfig,compareConfig,relabelConfig,firstLabel,secondLabel,Nat.add_assoc] using hh def divSubtractCost (ys zs : List Bool) : ℕ := (5*ys.length+2)+(subCost false zs ys+2*(subDigits false zs ys).length+1) lemma divSubtract_run (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) (xs ys zs ws : List Bool) (hzy : binaryValue ys≤binaryValue zs) (q c : ℕ) (bits : ℕ → Bool) : execution divSubtract O (divSubtractConfig (divRegisters R xs ys zs ws [] []) 0 q c) bits (divSubtractCost ys zs)= divSubtractConfig (divRegisters R xs ys (subDigits false zs ys) ws [] []) 24 q (c+divSubtractCost ys zs) := by have hc := copy_block (k:=k) (1 : Fin (k+8)) 4 5 (by simp) (by simp) (by simp) O (divRegisters R xs ys zs ws [] []) ys [] q c bits simp only [List.append_nil,divRegisters_copyS_in,divRegisters_copyS_out] at hc have hd := (subtraction_block (k:=k) (2 : Fin (k+8)) 5 4 (by simp) (by simp) (by simp) O (divRegisters R xs ys zs ws ys []) zs ys hzy q (c+(5*ys.length+2)) (fun i => bits (5*ys.length+2+i))).2.2 simp only [divRegisters_sub_in,divRegisters_sub_out] at hd have hh := concat_run (copyProgram (k:=k) 1 4 5) (subProgram 2 5 4) (by rfl) O (copyConfig (divRegisters R xs ys zs ws [] []) 0 q c) bits (5*ys.length+2) (subCost false zs ys+2*(subDigits false zs ys).length+1) (by rw [hc]; rfl) (by rw [hc]; rfl) rw [hc] at hh have hre : restartControl (copyConfig (divRegisters R xs ys zs ws ys []) 8 q (c+5*ys.length+2)) (0 : Fin 17)=subConfig (divRegisters R xs ys zs ws ys []) 0 q (c+(5*ys.length+2)) := by simp [restartControl,copyConfig,subConfig,Nat.add_assoc] rw [hre,hd] at hh simpa [divSubtract,divSubtractCost,divSubtractConfig,copyConfig,subConfig,relabelConfig,firstLabel,secondLabel,Nat.add_assoc] using hh def divisionCheckLabel (i : Fin 26) : Fin 54 := if h : i.val<24 then ⟨3+i.val,by omega⟩ else if i.val=24 then 27 else 52 def divisionSubLabel (i : Fin 25) : Fin 54 := ⟨27+i.val,by omega⟩ def divisionProgram : Program k 53 := fun i => if i.val=0 then .pop 0 53 1 2 else if i.val=1 then .push 2 false 3 else if i.val=2 then .push 2 true 3 else if h : i.val<27 then ((divCheck : Program k 25) ⟨i.val-3,by omega⟩).relabel divisionCheckLabel else if h : i.val<51 then ((divSubtract : Program k 24) ⟨i.val-27,by omega⟩).relabel divisionSubLabel else if i.val=51 then .push 3 true 0 else if i.val=52 then .push 3 false 0 else .halt def divisionConfig (R : Fin (k+8) → List Bool) (pc : Fin 54) (q c : ℕ) : MachineConfig k 53 := ⟨R,pc,none,q,c⟩ lemma division_check_table (i : Fin 26) (hi : (divCheck : Program k 25) i≠.halt) : (divisionProgram : Program k 53) (divisionCheckLabel i)= ((divCheck : Program k 25) i).relabel divisionCheckLabel := by have hil : i.val<24 := by by_contra hh have he : i=24 ∨ i=25 := by have hl := i.isLt rcases (show i.val=24 ∨ i.val=25 by omega) with h|h · exact Or.inl (Fin.ext h) · exact Or.inr (Fin.ext h) rcases he with rfl|rfl <;> exact hi rfl simp [divisionCheckLabel,hil,divisionProgram, show ¬3+i.val=1 by omega,show ¬3+i.val=2 by omega,show 3+i.val<27 by omega] lemma division_sub_table (i : Fin 25) (hi : i≠lastLabel 24) : (divisionProgram : Program k 53) (divisionSubLabel i)= ((divSubtract : Program k 24) i).relabel divisionSubLabel := by have hil : i.val<24 := by have hn : i.val≠24 := by intro h; exact hi (Fin.ext h) omega simp [divisionSubLabel,divisionProgram, show ¬27+i.val=1 by omega,show ¬27+i.val=2 by omega, show ¬27+i.val<27 by omega,show 27+i.val<51 by omega] lemma division_check_run (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) (xs ys zs ws : List Bool) (q c : ℕ) (bits : ℕ → Bool) : execution divisionProgram O (divisionConfig (divRegisters R xs ys zs ws [] []) 3 q c) bits (divCheckCost ys zs)=divisionConfig (divRegisters R xs ys zs ws [] []) (if binaryValue zs simpa [relabelConfig,divCheckConfig,divisionConfig,divisionCheckLabel] using h lemma division_sub_run (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) (xs ys zs ws : List Bool) (hzy : binaryValue ys≤binaryValue zs) (q c : ℕ) (bits : ℕ → Bool) : execution divisionProgram O (divisionConfig (divRegisters R xs ys zs ws [] []) 27 q c) bits (divSubtractCost ys zs)=divisionConfig (divRegisters R xs ys (subDigits false zs ys) ws [] []) 51 q (c+divSubtractCost ys zs) := by have h := execution_relabel_before_halt (divSubtract : Program k 24) divisionProgram divisionSubLabel (lastLabel 24) divSubtract_exit division_sub_table O (divSubtractConfig (divRegisters R xs ys zs ws [] []) 0 q c) bits (divSubtractCost ys zs) (by rw [divSubtract_run O R xs ys zs ws hzy]; rfl) rw [divSubtract_run O R xs ys zs ws hzy] at h simpa [relabelConfig,divSubtractConfig,divisionConfig,divisionSubLabel] using h def divisionRemainder (ys zs : List Bool) : List Bool := if binaryValue zs simp [execution,machineStep,divisionProgram,divisionConfig, divRegisters_update0,divRegisters_update2,divRegisters] unfold divisionDigitCost rw [show 2+divCheckCost ys (x::zs)+(if binaryValue (x::zs) (zs,ws) | x::xs,ys,zs,ws => divisionWords xs ys (divisionRemainder ys (x::zs)) (divisionDigit ys (x::zs)::ws) def divisionCost : List Bool → List Bool → List Bool → ℕ | [],_,_ => 1 | x::xs,ys,zs => divisionDigitCost ys (x::zs)+divisionCost xs ys (divisionRemainder ys (x::zs)) theorem division_machine_run (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) (xs ys zs ws : List Bool) (q c : ℕ) (bits : ℕ → Bool) : execution divisionProgram O (divisionConfig (divRegisters R xs ys zs ws [] []) 0 q c) bits (divisionCost xs ys zs)=divisionConfig (divRegisters R [] ys (divisionWords xs ys zs ws).1 (divisionWords xs ys zs ws).2 [] []) 53 q (c+divisionCost xs ys zs) := by induction xs generalizing zs ws c bits with | nil => simp [divisionCost,divisionWords,execution,machineStep,divisionProgram,divisionConfig,divRegisters] | cons x xs ih => rw [divisionCost,execution_add,division_digit_run,ih] simp only [divisionWords,Nat.add_assoc] lemma binaryValue_append (xs ys : List Bool) : binaryValue (xs++ys)=binaryValue xs+2^xs.length*binaryValue ys := by induction xs with | nil => simp [binaryValue] | cons x xs ih => simp only [List.cons_append,binaryValue,ih,List.length_cons,pow_succ] ring def streamValue : List Bool → ℕ → ℕ | [],a => a | x::xs,a => streamValue xs (2*a+(if x then 1 else 0)) lemma streamValue_eq (xs : List Bool) (a : ℕ) : streamValue xs a=binaryValue xs.reverse+2^xs.length*a := by induction xs generalizing a with | nil => simp [streamValue,binaryValue] | cons x xs ih => simp only [streamValue,ih,List.reverse_cons,binaryValue_append,List.length_reverse, List.length_cons,pow_succ,binaryValue] ring lemma division_step_math (x : Bool) (ys zs : List Bool) (hr : binaryValue zs simp [binaryValue] at hv <;> omega lemma divisionWords_invariant (xs ys zs ws : List Bool) (hr : binaryValue zs exact ⟨rfl,hr⟩ | cons x xs ih => have hd := division_step_math x ys zs hr have hi := ih (divisionRemainder ys (x::zs)) (divisionDigit ys (x::zs)::ws) hd.1 simp only [divisionWords] refine ⟨?_,hi.2⟩ rw [hi.1,streamValue] congr 1 simp only [binaryValue] have hv := hd.2 simp only [binaryValue] at hv nlinarith theorem divisionWords_correct (xs ys : List Bool) (hy : 0 induction ys generalizing c with | nil => simp [subDigits] | cons y ys ih => simp [subDigits,ih] | cons x xs ih => cases ys with | nil => simp [subDigits,ih] | cons y ys => simp [subDigits,ih,max_add_add_right] lemma divisionRemainder_length (ys zs : List Bool) : (divisionRemainder ys zs).length ≤ max zs.length ys.length := by unfold divisionRemainder split_ifs · exact Nat.le_max_left _ _ · exact (subDigits_length false zs ys).le lemma divCheckCost_bound (ys zs : List Bool) : divCheckCost ys zs≤12*max ys.length zs.length+6 := by have hy := Nat.le_max_left ys.length zs.length have hz := Nat.le_max_right ys.length zs.length unfold divCheckCost rw [Nat.max_comm zs.length ys.length] omega lemma divSubtractCost_bound (ys zs : List Bool) : divSubtractCost ys zs≤13*max ys.length zs.length+6 := by have hy := Nat.le_max_left ys.length zs.length have hz := Nat.le_max_right ys.length zs.length have h := (subDigits_length_cost false zs ys).2 unfold divSubtractCost rw [subDigits_length,Nat.max_comm zs.length ys.length] omega lemma divisionDigitCost_bound (ys zs : List Bool) : divisionDigitCost ys zs≤25*max ys.length zs.length+15 := by have hc := divCheckCost_bound ys zs have hs := divSubtractCost_bound ys zs unfold divisionDigitCost split_ifs <;> omega lemma divisionCost_bound (xs ys zs : List Bool) (K : ℕ) (hy : ys.length≤K) (hz : zs.length≤K) : divisionCost xs ys zs≤40*xs.length*(K+xs.length+1)+1 := by induction xs generalizing zs K with | nil => simp [divisionCost] | cons x xs ih => have hl : max ys.length (x::zs).length≤K+1 := by simp only [List.length_cons]; omega have hr : (divisionRemainder ys (x::zs)).length≤K+1 := by have hh := divisionRemainder_length ys (x::zs) rw [Nat.max_comm] at hh exact hh.trans hl have hc := (divisionDigitCost_bound ys (x::zs)).trans (Nat.add_le_add_right (Nat.mul_le_mul_left 25 hl) 15) have ht := ih (divisionRemainder ys (x::zs)) (K+1) (by omega) hr simp only [divisionCost,List.length_cons] nlinarith theorem division_block (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) (xs ys : List Bool) (hy : 0 .push (e i) b j | .pop i a b c => .pop (e i) a b c | .coin a b => .coin a b | .query w i a b => .query w (e i) a b | .halt => .halt def renameProgram (e : Equiv.Perm (Fin (k+8))) (P : Program k s) : Program k s := fun i => (P i).renameRegisters e def renameConfig (e : Equiv.Perm (Fin (k+8))) (c : MachineConfig k s) : MachineConfig k s := ⟨fun i => c.registers (e.symm i),c.control,c.output,c.oracleCalls,c.bitOperations⟩ lemma rename_update (e : Equiv.Perm (Fin (k+8))) (R : Fin (k+8) → List Bool) (j : Fin (k+8)) (z : List Bool) : Function.update (fun i => R (e.symm i)) (e j) z=(fun i => Function.update R j z (e.symm i)) := by funext i by_cases hi : i=e j · subst i; simp · have hj : e.symm i≠j := by intro h; apply hi; simpa using congrArg e h simp [Function.update,hi,hj] lemma machineStep_rename (e : Equiv.Perm (Fin (k+8))) (P : Program k s) (O : IndependenceOracle n) (b : Bool) (c : MachineConfig k s) (h : P c.control≠.halt) : machineStep (renameProgram e P) O b (renameConfig e c)=renameConfig e (machineStep P O b c) := by cases hc : c.output with | some z => simp [machineStep,renameConfig,hc] | none => cases hp : P c.control with | push i b j => simp [machineStep,renameConfig,hc,renameProgram,hp,Instruction.renameRegisters,rename_update] | pop i x y z => cases hl : c.registers i with | nil => simp [machineStep,renameConfig,hc,renameProgram,hp,Instruction.renameRegisters,hl] | cons a l => cases a <;> simp [machineStep,renameConfig,hc,renameProgram,hp,Instruction.renameRegisters,hl,rename_update] | coin x y => cases b <;> simp [machineStep,renameConfig,hc,renameProgram,hp,Instruction.renameRegisters] | query w i x y => by_cases hl : (c.registers i).length=n · simp [machineStep,renameConfig,hc,renameProgram,hp,Instruction.renameRegisters,hl] · simp [machineStep,renameConfig,hc,renameProgram,hp,Instruction.renameRegisters,hl] | halt => exact (h hp).elim theorem execution_rename_before_halt (e : Equiv.Perm (Fin (k+8))) (P : Program k s) (O : IndependenceOracle n) (c : MachineConfig k s) (bits : ℕ → Bool) (u : ℕ) (hu : (execution P O c bits u).output=none) : execution (renameProgram e P) O (renameConfig e c) bits u=renameConfig e (execution P O c bits u) := by induction u with | zero => rfl | succ u ih => have hn := machineStep_none_pre P O (bits u) (execution P O c bits u) hu have hh := machineStep_none_not_halt P O (bits u) (execution P O c bits u) hu simp only [execution,ih hn] exact machineStep_rename e P O _ _ hh end variable {k n : ℕ} def bitFrame : List Bool → List Bool | [] => [true] | b::bs => false::b::bitFrame bs lemma bitFrame_length (bs : List Bool) : (bitFrame bs).length=2*bs.length+1 := by induction bs with | nil => rfl | cons b bs ih => simp [bitFrame,ih]; omega lemma bitFrame_append (xs ys : List Bool) : bitFrame (xs++ys)=(xs.flatMap (fun b => [false,b]))++bitFrame ys := by induction xs with | nil => rfl | cons x xs ih => simp [bitFrame,ih] lemma bitFrame_reverse_cons (b : Bool) (bs : List Bool) : bitFrame (b::bs).reverse=(bs.reverse.flatMap (fun x => [false,x]))++[false,b,true] := by rw [List.reverse_cons,bitFrame_append] rfl def framePackProgram (a d : Fin (k+8)) : Program k 5 := fun pc => match pc.val with | 0 => .push d true 1 | 1 => .pop a 5 2 3 | 2 => .push d false 4 | 3 => .push d true 4 | 4 => .push d false 1 | _ => .halt def frameConfig (R : Fin (k+8) → List Bool) (pc : Fin 6) (q c : ℕ) : MachineConfig k 5 := ⟨R,pc,none,q,c⟩ lemma frame_pack_scan (a d : Fin (k+8)) (had : a≠d) (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) (xs ts : List Bool) (q c : ℕ) (bits : ℕ → Bool) : execution (framePackProgram a d) O (frameConfig (pairRegisters R a d xs ts) 1 q c) bits (3*xs.length+1)=frameConfig (pairRegisters R a d [] ((xs.reverse.flatMap (fun b => [false,b]))++ts)) 5 q (c+3*xs.length+1) := by induction xs generalizing ts c bits with | nil => simp [execution,machineStep,framePackProgram,frameConfig,pairRegisters_a _ _ _ had] | cons x xs ih => have ht : execution (framePackProgram a d) O (frameConfig (pairRegisters R a d (x::xs) ts) 1 q c) bits 3= frameConfig (pairRegisters R a d xs (false::x::ts)) 1 q (c+3) := by cases x <;> simp [execution,machineStep,framePackProgram,frameConfig, pairRegisters_a _ _ _ had,pairRegisters_b,pairRegisters_update_a _ _ _ had,pairRegisters_update_b] rw [List.length_cons,show 3*(xs.length+1)+1=3+(3*xs.length+1) by omega,execution_add,ht,ih] simp only [List.reverse_cons,List.flatMap_append,List.flatMap_singleton,List.append_assoc,List.cons_append,List.nil_append] congr 1 ; omega theorem frame_pack_block (a d : Fin (k+8)) (had : a≠d) (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) (xs ts : List Bool) (q c : ℕ) (bits : ℕ → Bool) : execution (framePackProgram a d) O (frameConfig (pairRegisters R a d xs ts) 0 q c) bits (3*xs.length+2)=frameConfig (pairRegisters R a d [] (bitFrame xs.reverse++ts)) 5 q (c+3*xs.length+2) := by have ht : execution (framePackProgram a d) O (frameConfig (pairRegisters R a d xs ts) 0 q c) bits 1= frameConfig (pairRegisters R a d xs (true::ts)) 1 q (c+1) := by simp [execution,machineStep,framePackProgram,frameConfig,pairRegisters_b,pairRegisters_update_b] rw [show 3*xs.length+2=1+(3*xs.length+1) by omega,execution_add,ht,frame_pack_scan a d had] have hf : bitFrame xs.reverse=(xs.reverse.flatMap (fun b => [false,b]))++[true] := by simpa [bitFrame] using bitFrame_append xs.reverse [] simp only [hf,List.append_assoc,List.singleton_append] congr 1 ; omega def frameUnpackProgram (a d : Fin (k+8)) : Program k 5 := fun pc => match pc.val with | 0 => .pop a 5 1 4 | 1 => .pop a 5 2 3 | 2 => .push d false 0 | 3 => .push d true 0 | _ => .halt theorem frame_unpack_block (a d : Fin (k+8)) (had : a≠d) (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) (xs ts zs : List Bool) (q c : ℕ) (bits : ℕ → Bool) : execution (frameUnpackProgram a d) O (frameConfig (pairRegisters R a d (bitFrame xs++ts) zs) 0 q c) bits (3*xs.length+1)= frameConfig (pairRegisters R a d ts (xs.reverse++zs)) 4 q (c+3*xs.length+1) := by induction xs generalizing zs c bits with | nil => simp [bitFrame,execution,machineStep,frameUnpackProgram,frameConfig, pairRegisters_a _ _ _ had,pairRegisters_update_a _ _ _ had] | cons x xs ih => have ht : execution (frameUnpackProgram a d) O (frameConfig (pairRegisters R a d (bitFrame (x::xs)++ts) zs) 0 q c) bits 3= frameConfig (pairRegisters R a d (bitFrame xs++ts) (x::zs)) 0 q (c+3) := by cases x <;> simp [bitFrame,execution,machineStep,frameUnpackProgram,frameConfig, pairRegisters_a _ _ _ had,pairRegisters_b,pairRegisters_update_a _ _ _ had,pairRegisters_update_b] rw [List.length_cons,show 3*(xs.length+1)+1=3+(3*xs.length+1) by omega,execution_add,ht,ih] simp only [List.reverse_cons,List.append_assoc,List.singleton_append] congr 1 ; omega theorem frame_unpack_packed (a d : Fin (k+8)) (had : a≠d) (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) (xs ts : List Bool) (q c : ℕ) (bits : ℕ → Bool) : execution (frameUnpackProgram a d) O (frameConfig (pairRegisters R a d (bitFrame xs.reverse++ts) []) 0 q c) bits (3*xs.length+1)= frameConfig (pairRegisters R a d ts xs) 4 q (c+3*xs.length+1) := by simpa using frame_unpack_block a d had O R xs.reverse ts [] q c bits end namespace MachineCode abbrev Registers (k : ℕ) := Fin (k+8) → List Bool structure Block (k : ℕ) where size : ℕ code : Program k size exit_halt : code (lastLabel size) = .halt def state {k s : ℕ} (R : Registers k) (pc : Fin (s+1)) (q w : ℕ) : MachineConfig k s := ⟨R,pc,none,q,w⟩ def Runs {k n : ℕ} (p : Block k) (O : IndependenceOracle n) (bits : ℕ → Bool) (R R' : Registers k) (t q w : ℕ) : Prop := ∀ q₀ w₀, execution p.code O (state R 0 q₀ w₀) bits t = state R' (lastLabel p.size) (q₀+q) (w₀+w) def skip (k : ℕ) : Block k := ⟨0,fun _ => .halt,rfl⟩ lemma runs_skip {k n : ℕ} (O : IndependenceOracle n) (bits : ℕ → Bool) (R : Registers k) : Runs (skip k) O bits R R 0 0 0 := by intro q w rfl def seq {k : ℕ} (p q : Block k) : Block k where size := p.size+q.size code := concatProgram p.code q.code exit_halt := by have he : lastLabel (p.size+q.size)=secondLabel p.size q.size (lastLabel q.size) := by apply Fin.ext; rfl rw [he,concatProgram_second,q.exit_halt] rfl lemma runs_seq {k n : ℕ} {p q : Block k} (O : IndependenceOracle n) (bits : ℕ → Bool) {R S T : Registers k} {u v a b c d : ℕ} (hp : Runs p O bits R S u a b) (hq : Runs q O (fun i => bits (u+i)) S T v c d) : Runs (seq p q) O bits R T (u+v) (a+c) (b+d) := by intro q₀ w₀ have ep := hp q₀ w₀ have en : (execution p.code O (state R 0 q₀ w₀) bits u).output=none := by rw [ep]; rfl have ec : (execution p.code O (state R 0 q₀ w₀) bits u).control=lastLabel p.size := by rw [ep]; rfl have h := concat_run p.code q.code p.exit_halt O (state R 0 q₀ w₀) bits u v en ec rw [ep] at h have eh := hq (q₀+a) (w₀+b) change execution q.code O (restartControl (state S (lastLabel p.size) (q₀+a) (w₀+b)) 0) (fun i => bits (u+i)) v = _ at eh rw [eh] at h change execution (concatProgram p.code q.code) O (state R 0 q₀ w₀) bits (u+v) = state T (lastLabel (p.size+q.size)) (q₀+(a+c)) (w₀+(b+d)) simpa [state,relabelConfig,firstLabel,secondLabel,lastLabel,Nat.add_assoc] using h def push {k : ℕ} (a : Fin (k+8)) (b : Bool) : Block k where size := 1 code := fun pc => if pc=0 then .push a b 1 else .halt exit_halt := by simp [lastLabel] lemma runs_push {k n : ℕ} (O : IndependenceOracle n) (bits : ℕ → Bool) (R : Registers k) (a : Fin (k+8)) (b : Bool) : Runs (push a b) O bits R (Function.update R a (b::R a)) 1 0 1 := by intro q w rfl inductive Test (k : ℕ) where | pop (a : Fin (k+8)) (empty zero one : Bool) | query (which : Bool) (a : Fin (k+8)) | coin def Test.instruction {k s : ℕ} (test : Test k) (no yes : Fin (s+1)) : Instruction k s := match test with | .pop a e z o => .pop a (if e then yes else no) (if z then yes else no) (if o then yes else no) | .query which a => .query which a no yes | .coin => .coin no yes def Test.result {k n : ℕ} (test : Test k) (O : IndependenceOracle n) (bit : Bool) (R : Registers k) : Option (Bool × Registers k) := match test with | .pop a e z o => match R a with | [] => some (e,R) | b::xs => some ((if b then o else z),Function.update R a xs) | .query which a => if (R a).length=n then some (O which (fun i => (R a)[i.val]?.getD false),R) else none | .coin => some (bit,R) def Test.queries {k : ℕ} : Test k → ℕ | .query _ _ => 1 | _ => 0 def Test.work {k : ℕ} (test : Test k) (n : ℕ) (R : Registers k) : ℕ := match test with | .query _ a => (R a).length+n+1 | _ => 1 lemma test_step {k s n : ℕ} (test : Test k) (O : IndependenceOracle n) (bit : Bool) (P : Program k s) (pc no yes : Fin (s+1)) (hP : P pc=test.instruction no yes) (R R' : Registers k) (b : Bool) (h : test.result O bit R=some (b,R')) (q w : ℕ) : machineStep P O bit (state R pc q w)= state R' (if b then yes else no) (q+test.queries) (w+test.work n R) := by cases test with | pop a e z o => cases ha : R a with | nil => simp only [Test.result,ha,Option.some.injEq,Prod.mk.injEq] at h rcases h with ⟨rfl,rfl⟩ simp [machineStep,state,hP,Test.instruction,ha,Test.queries,Test.work] | cons x xs => simp only [Test.result,ha,Option.some.injEq,Prod.mk.injEq] at h rcases h with ⟨rfl,rfl⟩ cases x <;> simp [machineStep,state,hP,Test.instruction,ha,Test.queries,Test.work] | query which a => simp only [Test.result] at h split_ifs at h with hn · simp only [Option.some.injEq,Prod.mk.injEq] at h rcases h with ⟨rfl,rfl⟩ simp [machineStep,state,hP,Test.instruction,hn,Test.queries,Test.work,Nat.add_assoc] | coin => simp only [Test.result,Option.some.injEq,Prod.mk.injEq] at h rcases h with ⟨rfl,rfl⟩ simp [machineStep,state,hP,Test.instruction,Test.queries,Test.work] def noLabel (s t : ℕ) (i : Fin (s+1)) : Fin (s+t+2) := if i.val=s then lastLabel (s+t+1) else ⟨i.val+1,by omega⟩ def yesLabel (s t : ℕ) (i : Fin (t+1)) : Fin (s+t+2) := if i.val=t then lastLabel (s+t+1) else ⟨s+i.val+1,by omega⟩ lemma noLabel_exit (s t : ℕ) : noLabel s t (lastLabel s)=lastLabel (s+t+1) := by simp [noLabel,lastLabel] lemma yesLabel_exit (s t : ℕ) : yesLabel s t (lastLabel t)=lastLabel (s+t+1) := by simp [yesLabel,lastLabel] def fork {k : ℕ} (test : Test k) (p q : Block k) : Block k where size := p.size+q.size+1 code := fun pc => if pc.val=0 then test.instruction (noLabel p.size q.size 0) (yesLabel p.size q.size 0) else if h : pc.val≤p.size then (p.code ⟨pc.val-1,by omega⟩).relabel (noLabel p.size q.size) else if h : pc.val≤p.size+q.size then (q.code ⟨pc.val-p.size-1,by omega⟩).relabel (yesLabel p.size q.size) else .halt exit_halt := by simp [lastLabel,show ¬p.size+q.size+1≤p.size by omega] lemma fork_head {k : ℕ} (test : Test k) (p q : Block k) : (fork test p q).code 0=test.instruction (noLabel p.size q.size 0) (yesLabel p.size q.size 0) := by simp [fork] lemma fork_no {k : ℕ} (test : Test k) (p q : Block k) (i : Fin (p.size+1)) (hi : i≠lastLabel p.size) : (fork test p q).code (noLabel p.size q.size i)=(p.code i).relabel (noLabel p.size q.size) := by have hv : i.val≠p.size := by intro h; exact hi (Fin.ext h) have hv' : i.val+1≤p.size := by omega simp [fork,noLabel,hv,hv'] lemma fork_yes {k : ℕ} (test : Test k) (p q : Block k) (i : Fin (q.size+1)) (hi : i≠lastLabel q.size) : (fork test p q).code (yesLabel p.size q.size i)=(q.code i).relabel (yesLabel p.size q.size) := by have hv : i.val≠q.size := by intro h; exact hi (Fin.ext h) have hv' : p.size+i.val+1≤p.size+q.size := by omega simp [fork,yesLabel,hv,show ¬p.size+i.val+1≤p.size by omega,hv',show p.size+i.val+1-p.size-1=i.val by omega] lemma fork_run_no {k n : ℕ} (test : Test k) (p q : Block k) (O : IndependenceOracle n) (bits : ℕ → Bool) {R S T : Registers k} {t a b : ℕ} (ht : test.result O (bits 0) R=some (false,S)) (hp : Runs p O (fun i => bits (1+i)) S T t a b) : Runs (fork test p q) O bits R T (1+t) (test.queries+a) (test.work n R+b) := by intro q₀ w₀ have first := test_step test O (bits 0) (fork test p q).code 0 _ _ (fork_head test p q) R S false ht q₀ w₀ have er := hp (q₀+test.queries) (w₀+test.work n R) have en : (execution p.code O (state S 0 (q₀+test.queries) (w₀+test.work n R)) (fun i => bits (1+i)) t).output=none := by rw [er]; rfl have rel := execution_relabel_before_halt p.code (fork test p q).code (noLabel p.size q.size) (lastLabel p.size) p.exit_halt (fork_no test p q) O _ (fun i => bits (1+i)) t en rw [er] at rel rw [execution_add] change execution (fork test p q).code O (machineStep (fork test p q).code O (bits 0) (state R 0 q₀ w₀)) (fun i => bits (1+i)) t = _ rw [first] change execution (fork test p q).code O (relabelConfig (noLabel p.size q.size) (state S 0 (q₀+test.queries) (w₀+test.work n R))) (fun i => bits (1+i)) t = _ rw [rel] simp only [state,relabelConfig,noLabel_exit,Nat.add_assoc] rfl lemma fork_run_yes {k n : ℕ} (test : Test k) (p q : Block k) (O : IndependenceOracle n) (bits : ℕ → Bool) {R S T : Registers k} {t a b : ℕ} (ht : test.result O (bits 0) R=some (true,S)) (hq : Runs q O (fun i => bits (1+i)) S T t a b) : Runs (fork test p q) O bits R T (1+t) (test.queries+a) (test.work n R+b) := by intro q₀ w₀ have first := test_step test O (bits 0) (fork test p q).code 0 _ _ (fork_head test p q) R S true ht q₀ w₀ have er := hq (q₀+test.queries) (w₀+test.work n R) have en : (execution q.code O (state S 0 (q₀+test.queries) (w₀+test.work n R)) (fun i => bits (1+i)) t).output=none := by rw [er]; rfl have rel := execution_relabel_before_halt q.code (fork test p q).code (yesLabel p.size q.size) (lastLabel q.size) q.exit_halt (fork_yes test p q) O _ (fun i => bits (1+i)) t en rw [er] at rel rw [execution_add] change execution (fork test p q).code O (machineStep (fork test p q).code O (bits 0) (state R 0 q₀ w₀)) (fun i => bits (1+i)) t = _ rw [first] change execution (fork test p q).code O (relabelConfig (yesLabel p.size q.size) (state S 0 (q₀+test.queries) (w₀+test.work n R))) (fun i => bits (1+i)) t = _ rw [rel] simp only [state,relabelConfig,yesLabel_exit,Nat.add_assoc] rfl end MachineCode section MachineLoops variable {k s n : ℕ} def loopLabel (s : ℕ) (i : Fin (s+1)) : Fin (s+2) := if h : i.val=s then 0 else ⟨i.val+1,by omega⟩ def repeatProgram (P : Program k s) (a : Fin (k+8)) : Program k (s+1) := fun pc => if pc.val=0 then .pop a (lastLabel (s+1)) (loopLabel s 0) (loopLabel s 0) else if h : pc.val≤ s then (P ⟨pc.val-1,by omega⟩).relabel (loopLabel s) else .halt lemma repeatProgram_body (P : Program k s) (a : Fin (k+8)) (i : Fin (s+1)) (hi : i≠lastLabel s) : repeatProgram P a (loopLabel s i)=(P i).relabel (loopLabel s) := by have hiv : i.val≠s := by intro h; apply hi; exact Fin.ext h simp [repeatProgram,loopLabel,hiv,show i.val+1≤ s by omega] lemma loopLabel_last (s : ℕ) : loopLabel s (lastLabel s)=0 := by simp [loopLabel,lastLabel] def loopConfig (R : Fin (k+8) → List Bool) (pc : Fin (s+1)) (q c : ℕ) : MachineConfig k s := ⟨R,pc,none,q,c⟩ lemma repeatProgram_pop (P : Program k s) (a : Fin (k+8)) (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) (x : Bool) (xs : List Bool) (q c : ℕ) (bits : ℕ → Bool) : execution (repeatProgram P a) O (loopConfig (Function.update R a (x::xs)) 0 q c) bits 1= relabelConfig (loopLabel s) (loopConfig (Function.update R a xs) 0 q (c+1)) := by cases x <;> simp [execution,machineStep,repeatProgram,loopConfig,relabelConfig] lemma repeatProgram_empty (P : Program k s) (a : Fin (k+8)) (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) (q c : ℕ) (bits : ℕ → Bool) : execution (repeatProgram P a) O (loopConfig (Function.update R a []) 0 q c) bits 1= loopConfig (Function.update R a []) (lastLabel (s+1)) q (c+1) := by simp [execution,machineStep,repeatProgram,loopConfig] def loopState {A : Type*} (f : A → A) : ℕ → A → A | 0,x => x | m+1,x => loopState f m (f x) def loopSum {A : Type*} (f : A → A) (g : A → ℕ) : ℕ → A → ℕ | 0,_ => 0 | m+1,x => g x+loopSum f g m (f x) theorem repeat_block {A : Type*} (P : Program k s) (a : Fin (k+8)) (hexit : P (lastLabel s)=.halt) (O : IndependenceOracle n) (encode : A → Fin (k+8) → List Bool) (f : A → A) (ticks queries work : A → ℕ) (body : ∀ (v : A) (xs : List Bool) (q c : ℕ) (bits : ℕ → Bool), execution P O (loopConfig (Function.update (encode v) a xs) 0 q c) bits (ticks v)= loopConfig (Function.update (encode (f v)) a xs) (lastLabel s) (q+queries v) (c+work v)) (v : A) (xs : List Bool) (q c : ℕ) (bits : ℕ → Bool) : execution (repeatProgram P a) O (loopConfig (Function.update (encode v) a xs) 0 q c) bits (loopSum f (fun v => ticks v+1) xs.length v+1)= loopConfig (Function.update (encode (loopState f xs.length v)) a []) (lastLabel (s+1)) (q+loopSum f queries xs.length v) (c+loopSum f (fun v => work v+1) xs.length v+1) := by induction xs generalizing v q c bits with | nil => simpa [loopSum,loopState] using repeatProgram_empty P a O (encode v) q c bits | cons x xs ih => have hb := body v xs q (c+1) (fun i => bits (1+i)) have hnone : (execution P O (loopConfig (Function.update (encode v) a xs) 0 q (c+1)) (fun i => bits (1+i)) (ticks v)).output=none := by rw [hb]; rfl have hl := execution_relabel_before_halt P (repeatProgram P a) (loopLabel s) (lastLabel s) hexit (repeatProgram_body P a) O _ (fun i => bits (1+i)) (ticks v) hnone have hfirst : execution (repeatProgram P a) O (loopConfig (Function.update (encode v) a (x::xs)) 0 q c) bits (1+ticks v)= loopConfig (Function.update (encode (f v)) a xs) 0 (q+queries v) (c+1+work v) := by rw [execution_add,repeatProgram_pop,hl,hb] simp [relabelConfig,loopConfig,loopLabel_last] simp only [List.length_cons,loopSum,loopState] rw [show ticks v+1+loopSum f (fun v => ticks v+1) xs.length (f v)+1= (1+ticks v)+(loopSum f (fun v => ticks v+1) xs.length (f v)+1) by omega, execution_add,hfirst,ih] congr 1 <;> omega lemma loopSum_le {A : Type*} (f : A → A) (g : A → ℕ) (B : ℕ) (hg : ∀ x,g x≤B) (m : ℕ) (x : A) : loopSum f g m x≤ m*B := by induction m generalizing x with | zero => simp [loopSum] | succ m ih => simpa [loopSum,Nat.succ_mul,Nat.add_comm] using Nat.add_le_add (hg x) (ih (f x)) end MachineLoops section MachineMove variable {k n : ℕ} def reverseProgram (a d : Fin (k+8)) : Program k 3 := fun pc => match pc.val with | 0 => .pop a 3 1 2 | 1 => .push d false 0 | 2 => .push d true 0 | _ => .halt def reverseConfig (R : Fin (k+8) → List Bool) (pc : Fin 4) (q c : ℕ) : MachineConfig k 3 := ⟨R,pc,none,q,c⟩ theorem reverse_block (a d : Fin (k+8)) (had : a≠d) (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) (xs ys : List Bool) (q c : ℕ) (bits : ℕ → Bool) : execution (reverseProgram a d) O (reverseConfig (pairRegisters R a d xs ys) 0 q c) bits (2*xs.length+1)= reverseConfig (pairRegisters R a d [] (xs.reverse++ys)) 3 q (c+2*xs.length+1) := by induction xs generalizing ys c bits with | nil => simp [execution,machineStep,reverseProgram,reverseConfig,pairRegisters_a _ _ _ had] | cons x xs ih => have ht : execution (reverseProgram a d) O (reverseConfig (pairRegisters R a d (x::xs) ys) 0 q c) bits 2= reverseConfig (pairRegisters R a d xs (x::ys)) 0 q (c+2) := by cases x <;> simp [execution,machineStep,reverseProgram,reverseConfig,pairRegisters_a _ _ _ had,pairRegisters_b, pairRegisters_update_a _ _ _ had,pairRegisters_update_b] rw [List.length_cons,show 2*(xs.length+1)+1=2+(2*xs.length+1) by omega,execution_add,ht,ih] simp only [List.reverse_cons,List.append_assoc,List.singleton_append] congr 1; omega def clearProgram (a : Fin (k+8)) : Program k 1 := fun pc => if pc.val=0 then .pop a 1 0 0 else .halt def clearConfig (R : Fin (k+8) → List Bool) (pc : Fin 2) (q c : ℕ) : MachineConfig k 1 := ⟨R,pc,none,q,c⟩ theorem clear_block (a : Fin (k+8)) (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) (xs : List Bool) (q c : ℕ) (bits : ℕ → Bool) : execution (clearProgram a) O (clearConfig (Function.update R a xs) 0 q c) bits (xs.length+1)= clearConfig (Function.update R a []) 1 q (c+xs.length+1) := by induction xs generalizing c bits with | nil => simp [execution,machineStep,clearProgram,clearConfig] | cons x xs ih => have ht : execution (clearProgram a) O (clearConfig (Function.update R a (x::xs)) 0 q c) bits 1= clearConfig (Function.update R a xs) 0 q (c+1) := by cases x <;> simp [execution,machineStep,clearProgram,clearConfig] rw [List.length_cons,show xs.length+1+1=1+(xs.length+1) by omega,execution_add,ht,ih] congr 1; omega def moveProgram (a b d : Fin (k+8)) : Program k 6 := concatProgram (reverseProgram a b) (reverseProgram b d) def moveConfig (R : Fin (k+8) → List Bool) (pc : Fin 7) (q c : ℕ) : MachineConfig k 6 := ⟨R,pc,none,q,c⟩ lemma triple_pair_ab (R : Fin (k+8) → List Bool) (a b d : Fin (k+8)) (hab : a≠b) (had : a≠d) (hbd : b≠d) (xs ys zs us vs : List Bool) : pairRegisters (tripleRegisters R a b d xs ys zs) a b us vs=tripleRegisters R a b d us vs zs := by simp only [pairRegisters,tripleRegisters_update_a _ _ _ _ hab had,tripleRegisters_update_b _ _ _ _ hbd] lemma triple_pair_bd (R : Fin (k+8) → List Bool) (a b d : Fin (k+8)) (hbd : b≠d) (xs ys zs us vs : List Bool) : pairRegisters (tripleRegisters R a b d xs ys zs) b d us vs=tripleRegisters R a b d xs us vs := by simp only [pairRegisters,tripleRegisters_update_b _ _ _ _ hbd,tripleRegisters_update_d] theorem move_block (a b d : Fin (k+8)) (hab : a≠b) (had : a≠d) (hbd : b≠d) (O : IndependenceOracle n) (R : Fin (k+8) → List Bool) (xs ys : List Bool) (q c : ℕ) (bits : ℕ → Bool) : execution (moveProgram a b d) O (moveConfig (tripleRegisters R a b d xs [] ys) 0 q c) bits (4*xs.length+2)= moveConfig (tripleRegisters R a b d [] [] (xs++ys)) 6 q (c+4*xs.length+2) := by have h1 := reverse_block a b hab O (tripleRegisters R a b d xs [] ys) xs [] q c bits simp only [triple_pair_ab _ _ _ _ hab had hbd,List.append_nil] at h1 have h2 := reverse_block b d hbd O (tripleRegisters R a b d [] xs.reverse ys) xs.reverse ys q (c+2*xs.length+1) (fun i => bits (2*xs.length+1+i)) simp only [triple_pair_bd _ _ _ _ hbd,List.reverse_reverse,List.length_reverse] at h2 have h := concat_run (reverseProgram a b) (reverseProgram b d) (by rfl) O (reverseConfig (tripleRegisters R a b d xs [] ys) 0 q c) bits (2*xs.length+1) (2*xs.length+1) (by rw [h1]; rfl) (by rw [h1]; rfl) rw [h1] at h change execution (moveProgram a b d) O (moveConfig (tripleRegisters R a b d xs [] ys) 0 q c) bits ((2*xs.length+1)+(2*xs.length+1))=relabelConfig (secondLabel 3 3) (execution (reverseProgram b d) O (reverseConfig (tripleRegisters R a b d [] xs.reverse ys) 0 q (c+2*xs.length+1)) (fun i => bits (2*xs.length+1+i)) (2*xs.length+1)) at h rw [h2] at h convert h using 1 <;> simp only [relabelConfig,reverseConfig,moveConfig,secondLabel, show 2*xs.length+1+(2*xs.length+1)=4*xs.length+2 by omega, show c+2*xs.length+1+2*xs.length+1=c+4*xs.length+2 by omega] rfl end MachineMove namespace MachineCode def reverse {k : ℕ} (a d : Fin (k+8)) : Block k := ⟨3,reverseProgram a d,rfl⟩ def clear {k : ℕ} (a : Fin (k+8)) : Block k := ⟨1,clearProgram a,rfl⟩ def move {k : ℕ} (a b d : Fin (k+8)) : Block k := ⟨6,moveProgram a b d,rfl⟩ def pack {k : ℕ} (a d : Fin (k+8)) : Block k := ⟨5,framePackProgram a d,rfl⟩ def unpack {k : ℕ} (a d : Fin (k+8)) : Block k where size := 4 code := fun pc => match pc.val with | 0 => .pop a 4 1 4 | 1 => .pop a 4 2 3 | 2 => .push d false 0 | 3 => .push d true 0 | _ => .halt exit_halt := rfl lemma runs_reverse {k n : ℕ} (a d : Fin (k+8)) (had : a≠d) (O : IndependenceOracle n) (R : Registers k) (xs ys : List Bool) (bits : ℕ → Bool) : Runs (reverse a d) O bits (pairRegisters R a d xs ys) (pairRegisters R a d [] (xs.reverse++ys)) (2*xs.length+1) 0 (2*xs.length+1) := by intro q w convert reverse_block a d had O R xs ys q w bits using 1 <;> simp [reverse,state,reverseConfig,lastLabel,Nat.add_assoc] rfl lemma runs_clear {k n : ℕ} (a : Fin (k+8)) (O : IndependenceOracle n) (R : Registers k) (xs : List Bool) (bits : ℕ → Bool) : Runs (clear a) O bits (Function.update R a xs) (Function.update R a []) (xs.length+1) 0 (xs.length+1) := by intro q w convert clear_block a O R xs q w bits using 1 <;> simp [clear,state,clearConfig,lastLabel,Nat.add_assoc] rfl lemma runs_move {k n : ℕ} (a b d : Fin (k+8)) (hab : a≠b) (had : a≠d) (hbd : b≠d) (O : IndependenceOracle n) (R : Registers k) (xs ys : List Bool) (bits : ℕ → Bool) : Runs (move a b d) O bits (tripleRegisters R a b d xs [] ys) (tripleRegisters R a b d [] [] (xs++ys)) (4*xs.length+2) 0 (4*xs.length+2) := by intro q w convert move_block a b d hab had hbd O R xs ys q w bits using 1 <;> simp [move,state,moveConfig,lastLabel,Nat.add_assoc] rfl lemma runs_pack {k n : ℕ} (a d : Fin (k+8)) (had : a≠d) (O : IndependenceOracle n) (R : Registers k) (xs ts : List Bool) (bits : ℕ → Bool) : Runs (pack a d) O bits (pairRegisters R a d xs ts) (pairRegisters R a d [] (bitFrame xs.reverse++ts)) (3*xs.length+2) 0 (3*xs.length+2) := by intro q w convert frame_pack_block a d had O R xs ts q w bits using 1 <;> simp [pack,state,frameConfig,lastLabel,Nat.add_assoc] rfl lemma runs_unpack {k n : ℕ} (a d : Fin (k+8)) (had : a≠d) (O : IndependenceOracle n) (R : Registers k) (xs ts zs : List Bool) (bits : ℕ → Bool) : Runs (unpack a d) O bits (pairRegisters R a d (bitFrame xs++ts) zs) (pairRegisters R a d ts (xs.reverse++zs)) (3*xs.length+1) 0 (3*xs.length+1) := by intro q w let f : Fin 6 → Fin 5 := fun i => ⟨min i.val 4,by omega⟩ have h := frame_unpack_block a d had O R xs ts zs q w bits have hn : (execution (frameUnpackProgram a d) O (frameConfig (pairRegisters R a d (bitFrame xs++ts) zs) 0 q w) bits (3*xs.length+1)).output=none := by rw [h]; rfl have rel := execution_relabel_before_halt (frameUnpackProgram a d) (unpack a d).code f 4 rfl (by intro i hi; fin_cases i <;> rfl) O _ bits (3*xs.length+1) hn rw [h] at rel convert rel using 1 <;> simp [state,relabelConfig,frameConfig,f,unpack,lastLabel,Nat.add_assoc] rfl lemma runs_unpack_packed {k n : ℕ} (a d : Fin (k+8)) (had : a≠d) (O : IndependenceOracle n) (R : Registers k) (xs ts : List Bool) (bits : ℕ → Bool) : Runs (unpack a d) O bits (pairRegisters R a d (bitFrame xs.reverse++ts) []) (pairRegisters R a d ts xs) (3*xs.length+1) 0 (3*xs.length+1) := by simpa only [List.length_reverse,List.reverse_reverse,List.append_nil] using runs_unpack a d had O R xs.reverse ts [] bits def repeatBlock {k : ℕ} (p : Block k) (a : Fin (k+8)) : Block k where size := p.size+1 code := repeatProgram p.code a exit_halt := by simp [repeatProgram,lastLabel] abbrev Word := List Bool def regs (x y z saved : Word) : Registers 1 := fun i => if i=0 then x else if i=1 then y else if i=2 then z else if i=8 then saved else [] @[simp] lemma regs_zero (x y z s : Word) : regs x y z s 0=x := by simp [regs] @[simp] lemma regs_one (x y z s : Word) : regs x y z s 1=y := by simp [regs] @[simp] lemma regs_two (x y z s : Word) : regs x y z s 2=z := by simp [regs] @[simp] lemma regs_eight (x y z s : Word) : regs x y z s 8=s := by simp [regs] @[simp] lemma update_regs_zero (x y z s u : Word) : Function.update (regs x y z s) 0 u=regs u y z s := by funext i; fin_cases i <;> simp [regs] @[simp] lemma update_regs_one (x y z s u : Word) : Function.update (regs x y z s) 1 u=regs x u z s := by funext i; fin_cases i <;> simp [regs] @[simp] lemma update_regs_two (x y z s u : Word) : Function.update (regs x y z s) 2 u=regs x y u s := by funext i; fin_cases i <;> simp [regs] @[simp] lemma update_regs_eight (x y z s u : Word) : Function.update (regs x y z s) 8 u=regs x y z u := by funext i; fin_cases i <;> simp [regs] def pair (x y : Word) : Word := bitFrame x.reverse++y @[simp] lemma pair_length (x y : Word) : (pair x y).length=2*x.length+1+y.length := by simp [pair,bitFrame_length] def Computes {n : ℕ} (p : Block 1) (O : IndependenceOracle n) (x y : Word) (t q w : ℕ) : Prop := ∀ saved bits, Runs p O bits (regs x [] [] saved) (regs y [] [] saved) t q w def Bounded {n : ℕ} (p : Block 1) (O : IndependenceOracle n) (x y : Word) (B : ℕ) : Prop := ∃ t q w, t≤B ∧ q≤B ∧ w≤B ∧ Computes p O x y t q w lemma computes_skip {n : ℕ} (O : IndependenceOracle n) (x : Word) : Computes (skip 1) O x x 0 0 0 := fun s bits => runs_skip O bits (regs x [] [] s) lemma computes_seq {n : ℕ} {p q : Block 1} {O : IndependenceOracle n} {x y z : Word} {t₁ q₁ w₁ t₂ q₂ w₂ : ℕ} (hp : Computes p O x y t₁ q₁ w₁) (hq : Computes q O y z t₂ q₂ w₂) : Computes (seq p q) O x z (t₁+t₂) (q₁+q₂) (w₁+w₂) := by intro s bits exact runs_seq O bits (hp s bits) (hq s (fun i => bits (t₁+i))) lemma bounded_seq {n : ℕ} {p q : Block 1} {O : IndependenceOracle n} {x y z : Word} {B C : ℕ} (hp : Bounded p O x y B) (hq : Bounded q O y z C) : Bounded (seq p q) O x z (B+C) := by obtain ⟨t₁,q₁,w₁,ht₁,hq₁,hw₁,hp⟩ := hp obtain ⟨t₂,q₂,w₂,ht₂,hq₂,hw₂,hq⟩ := hq exact ⟨_,_,_,Nat.add_le_add ht₁ ht₂,Nat.add_le_add hq₁ hq₂,Nat.add_le_add hw₁ hw₂,computes_seq hp hq⟩ lemma bounded_mono {n : ℕ} {p : Block 1} {O : IndependenceOracle n} {x y : Word} {B C : ℕ} (h : Bounded p O x y B) (hBC : B≤C) : Bounded p O x y C := by obtain ⟨t,q,w,ht,hq,hw,hp⟩ := h exact ⟨t,q,w,ht.trans hBC,hq.trans hBC,hw.trans hBC,hp⟩ def copy {k : ℕ} (a b d : Fin (k+8)) : Block k := ⟨8,copyProgram a b d,rfl⟩ lemma runs_copy {k n : ℕ} (a b d : Fin (k+8)) (hab : a≠b) (had : a≠d) (hbd : b≠d) (O : IndependenceOracle n) (R : Registers k) (xs ys : Word) (bits : ℕ → Bool) : Runs (copy a b d) O bits (tripleRegisters R a b d xs [] ys) (tripleRegisters R a b d xs [] (xs++ys)) (5*xs.length+2) 0 (5*xs.length+2) := by intro q w convert copy_block a b d hab had hbd O R xs ys q w bits using 1 <;> simp [copy,state,copyConfig,lastLabel,Nat.add_assoc] rfl def duplicate : Block 1 := seq (copy 0 2 1) (pack 1 0) lemma computes_duplicate {n : ℕ} (O : IndependenceOracle n) (x : Word) : Computes duplicate O x (pair x x) (8*x.length+4) 0 (8*x.length+4) := by intro s bits have hc := runs_copy (k:=1) 0 2 1 (by decide) (by decide) (by decide) O (regs x [] [] s) x [] bits simp only [tripleRegisters,pairRegisters,update_regs_zero,update_regs_two,update_regs_one,List.append_nil] at hc have hp := runs_pack (k:=1) 1 0 (by decide) O (regs x x [] s) x x (fun i => bits (5*x.length+2+i)) simp only [pairRegisters,update_regs_one,update_regs_zero] at hp simpa only [duplicate,pair,show 5*x.length+2+(3*x.length+2)=8*x.length+4 by omega,Nat.zero_add] using runs_seq O bits hc hp lemma split_pair {n : ℕ} (O : IndependenceOracle n) (x y z s : Word) (bits : ℕ → Bool) : Runs (unpack 0 1) O bits (regs (pair x y) z [] s) (regs y (x++z) [] s) (3*x.length+1) 0 (3*x.length+1) := by have h := runs_unpack (k:=1) 0 1 (by decide) O (regs [] [] [] s) x.reverse y z bits simpa only [pair,pairRegisters,update_regs_zero,update_regs_one,List.length_reverse,List.reverse_reverse] using h lemma make_pair {n : ℕ} (O : IndependenceOracle n) (x y z s : Word) (bits : ℕ → Bool) : Runs (pack 1 0) O bits (regs y x z s) (regs (pair x y) [] z s) (3*x.length+2) 0 (3*x.length+2) := by simpa only [pair,pairRegisters,update_regs_zero,update_regs_one] using runs_pack (k:=1) 1 0 (by decide) O (regs [] [] z s) x y bits lemma move_one_zero {n : ℕ} (O : IndependenceOracle n) (x y s : Word) (bits : ℕ → Bool) : Runs (move 1 2 0) O bits (regs y x [] s) (regs (x++y) [] [] s) (4*x.length+2) 0 (4*x.length+2) := by simpa only [tripleRegisters,pairRegisters,update_regs_zero,update_regs_one,update_regs_two] using runs_move (k:=1) 1 2 0 (by decide) (by decide) (by decide) O (regs [] [] [] s) x y bits def first : Block 1 := seq (unpack 0 1) (seq (clear 0) (move 1 2 0)) def second : Block 1 := seq (unpack 0 1) (clear 1) lemma computes_first {n : ℕ} (O : IndependenceOracle n) (x y : Word) : Computes first O (pair x y) x (7*x.length+y.length+4) 0 (7*x.length+y.length+4) := by intro s bits have hu := split_pair O x y [] s bits have hc := runs_clear (k:=1) 0 O (regs y x [] s) y (fun i => bits (3*x.length+1+i)) simp only [update_regs_zero] at hc have hm := move_one_zero O x [] s (fun i => bits (3*x.length+1+(y.length+1+i))) simp only [List.append_nil] at hu hm have ht := runs_seq O bits hu (runs_seq O (fun i => bits (3*x.length+1+i)) hc hm) simpa only [first,show 3*x.length+1+(y.length+1+(4*x.length+2))=7*x.length+y.length+4 by omega,Nat.zero_add] using ht lemma computes_second {n : ℕ} (O : IndependenceOracle n) (x y : Word) : Computes second O (pair x y) y (4*x.length+2) 0 (4*x.length+2) := by intro s bits have hu := split_pair O x y [] s bits simp only [List.append_nil] at hu have hc := runs_clear (k:=1) 1 O (regs y x [] s) x (fun i => bits (3*x.length+1+i)) simp only [update_regs_one] at hc simpa only [second,show 3*x.length+1+(x.length+1)=4*x.length+2 by omega,Nat.zero_add] using runs_seq O bits hu hc lemma save_zero {n : ℕ} (O : IndependenceOracle n) (x y s : Word) (bits : ℕ → Bool) : Runs (pack 0 8) O bits (regs x y [] s) (regs [] y [] (pair x s)) (3*x.length+2) 0 (3*x.length+2) := by simpa only [pair,pairRegisters,update_regs_zero,update_regs_eight] using runs_pack (k:=1) 0 8 (by decide) O (regs [] y [] []) x s bits lemma restore_one {n : ℕ} (O : IndependenceOracle n) (x y s : Word) (bits : ℕ → Bool) : Runs (unpack 8 1) O bits (regs x [] [] (pair y s)) (regs x y [] s) (3*y.length+1) 0 (3*y.length+1) := by simpa only [pair,pairRegisters,update_regs_one,update_regs_eight] using runs_unpack_packed (k:=1) 8 1 (by decide) O (regs x [] [] []) y s bits lemma pack_zero_one {n : ℕ} (O : IndependenceOracle n) (x y s : Word) (bits : ℕ → Bool) : Runs (pack 0 1) O bits (regs x y [] s) (regs [] (pair x y) [] s) (3*x.length+2) 0 (3*x.length+2) := by simpa only [pair,pairRegisters,update_regs_zero,update_regs_one] using runs_pack (k:=1) 0 1 (by decide) O (regs [] [] [] s) x y bits def swap : Block 1 := seq (unpack 0 1) (seq (pack 0 1) (move 1 2 0)) lemma computes_swap {n : ℕ} (O : IndependenceOracle n) (x y : Word) : Computes swap O (pair x y) (pair y x) (7*x.length+11*y.length+9) 0 (7*x.length+11*y.length+9) := by intro s bits have hu := split_pair O x y [] s bits simp only [List.append_nil] at hu have hp := pack_zero_one O y x s (fun i => bits (3*x.length+1+i)) have hm := move_one_zero O (pair y x) [] s (fun i => bits (3*x.length+1+(3*y.length+2+i))) simp only [List.append_nil] at hm have ht := runs_seq O bits hu (runs_seq O (fun i => bits (3*x.length+1+i)) hp hm) have he : 3*x.length+1+(3*y.length+2+(4*(pair y x).length+2))=7*x.length+11*y.length+9 := by rw [pair_length]; omega simpa only [swap,he,Nat.zero_add] using ht def left (p : Block 1) : Block 1 := seq (unpack 0 1) (seq (pack 0 8) (seq (move 1 2 0) (seq p (seq (unpack 8 1) (seq (pack 0 1) (move 1 2 0)))))) lemma computes_left {n : ℕ} {O : IndependenceOracle n} {p : Block 1} {x u : Word} {t q w : ℕ} (h : Computes p O x u t q w) (y : Word) : Computes (left p) O (pair x y) (pair u y) (7*x.length+10*y.length+11*u.length+14+t) q (7*x.length+10*y.length+11*u.length+14+w) := by intro s bits have hu := split_pair O x y [] s bits simp only [List.append_nil] at hu have hs := save_zero O y x s (fun i => bits (3*x.length+1+i)) have hm := move_one_zero O x [] (pair y s) (fun i => bits (3*x.length+1+(3*y.length+2+i))) simp only [List.append_nil] at hm have hp := h (pair y s) (fun i => bits (3*x.length+1+(3*y.length+2+(4*x.length+2+i)))) have hr := restore_one O u y s (fun i => bits (3*x.length+1+(3*y.length+2+(4*x.length+2+(t+i))))) have hf := pack_zero_one O u y s (fun i => bits (3*x.length+1+(3*y.length+2+(4*x.length+2+(t+(3*y.length+1+i)))))) have he := move_one_zero O (pair u y) [] s (fun i => bits (3*x.length+1+(3*y.length+2+(4*x.length+2+(t+(3*y.length+1+(3*u.length+2+i))))))) simp only [List.append_nil] at he have ht := runs_seq O bits hu (runs_seq O _ hs (runs_seq O _ hm (runs_seq O _ hp (runs_seq O _ hr (runs_seq O _ hf he))))) have cost (v : ℕ) : 3*x.length+1+(3*y.length+2+(4*x.length+2+(v+(3*y.length+1+(3*u.length+2+(4*(pair u y).length+2))))))= 7*x.length+10*y.length+11*u.length+14+v := by rw [pair_length]; omega simpa only [left,cost,Nat.zero_add,Nat.add_zero] using ht def right (p : Block 1) : Block 1 := seq swap (seq (left p) swap) lemma computes_right {n : ℕ} {O : IndependenceOracle n} {p : Block 1} {x u : Word} {t q w : ℕ} (h : Computes p O x u t q w) (y : Word) : Computes (right p) O (pair y x) (pair y u) (28*y.length+18*x.length+18*u.length+32+t) q (28*y.length+18*x.length+18*u.length+32+w) := by have ht := computes_seq (computes_swap O y x) (computes_seq (computes_left h y) (computes_swap O u y)) convert ht using 1 <;> first | rfl | omega def parallel (p q : Block 1) : Block 1 := seq (left p) (right q) def fanout (p q : Block 1) : Block 1 := seq duplicate (parallel p q) def stripZeros : Word → Word | [] => [] | false::xs => stripZeros xs | true::xs => true::xs def stripCost : Word → ℕ | [] => 1 | false::xs => 1+stripCost xs | true::_ => 2 lemma strip_length (x : Word) : (stripZeros x).length≤x.length := by induction x with | nil => rfl | cons b xs ih => cases b <;> simp only [stripZeros,List.length_cons] <;> omega lemma strip_cost_le (x : Word) : stripCost x≤x.length+2 := by induction x with | nil => decide | cons b xs ih => cases b <;> simp only [stripCost,List.length_cons] <;> omega lemma strip_append (x y : Word) : stripZeros (x++y)=if stripZeros x=[] then stripZeros y else stripZeros x++y := by induction x with | nil => simp [stripZeros] | cons b xs ih => cases b <;> simp [stripZeros,ih] rfl def normalWord (x : Word) : Word := (stripZeros x.reverse).reverse lemma normal_length (x : Word) : (normalWord x).length≤x.length := by simpa only [normalWord,List.length_reverse] using strip_length x.reverse lemma normalWord_cons (b : Bool) (xs : Word) : normalWord (b::xs)=if normalWord xs=[] then (if b then [true] else []) else b::normalWord xs := by simp only [normalWord,List.reverse_cons,strip_append] by_cases h : stripZeros xs.reverse=[] · simp [h]; cases b <;> rfl · simp [h,List.reverse_eq_nil_iff] lemma binaryValue_bits (n : ℕ) : binaryValue n.bits=n := by induction n using Nat.binaryRec' with | zero => rfl | bit b n hn ih => rw [Nat.bits_append_bit n b hn] cases b <;> simp [binaryValue,ih,Nat.bit] omega lemma normalWord_eq_bits (xs : Word) : normalWord xs=(binaryValue xs).bits := by induction xs with | nil => rfl | cons b xs ih => rw [normalWord_cons,ih] by_cases hz : binaryValue xs=0 · cases b <;> simp [binaryValue,hz] · have hb : (binaryValue xs).bits≠[] := by intro h have he := binaryValue_bits (binaryValue xs) rw [h] at he exact hz he.symm cases b with | false => simp [binaryValue,hb,Nat.bit0_bits _ hz] | true => simp only [ite_true,ite_eq_right hb,binaryValue] rw [Nat.add_comm 1, Nat.bit1_bits] lemma normalWord_value (xs : Word) : binaryValue (normalWord xs)=binaryValue xs := by rw [normalWord_eq_bits,binaryValue_bits] @[simp] lemma normalWord_bits (n : ℕ) : normalWord n.bits=n.bits := by rw [normalWord_eq_bits,binaryValue_bits] def stripCode {k : ℕ} (a : Fin (k+8)) : Block k where size := 2 code := fun pc => match pc.val with | 0 => .pop a 2 0 1 | 1 => .push a true 2 | _ => .halt exit_halt := rfl lemma runs_strip {k n : ℕ} (a : Fin (k+8)) (O : IndependenceOracle n) (R : Registers k) (x : Word) (bits : ℕ → Bool) : Runs (stripCode a) O bits (Function.update R a x) (Function.update R a (stripZeros x)) (stripCost x) 0 (stripCost x) := by intro q w induction x generalizing w bits with | nil => simp [stripCode,stripCost,stripZeros,execution,machineStep,state,lastLabel] | cons b xs ih => cases b with | false => have hf : execution (stripCode a).code O (state (Function.update R a (false::xs)) 0 q w) bits 1= state (Function.update R a xs) 0 q (w+1) := by simp [stripCode,state,execution,machineStep] rfl rw [stripCost,execution_add,hf,ih] simp [stripZeros,Nat.add_assoc] | true => simp [stripCode,stripCost,stripZeros,execution,machineStep,state,lastLabel,Nat.add_assoc] def normalCode : Block 1 := seq (reverse 0 1) (seq (stripCode 1) (reverse 1 0)) def normalCost (x : Word) : ℕ := 2*x.length+1+(stripCost x.reverse+(2*(stripZeros x.reverse).length+1)) lemma normalCost_le (x : Word) : normalCost x≤5*x.length+4 := by have h₁:=strip_cost_le x.reverse have h₂:=strip_length x.reverse simp only [List.length_reverse] at h₁ h₂ unfold normalCost omega lemma computes_normalCode {n : ℕ} (O : IndependenceOracle n) (x : Word) : Computes normalCode O x (normalWord x) (normalCost x) 0 (normalCost x) := by intro s bits have h₁ := runs_reverse (k:=1) 0 1 (by decide) O (regs [] [] [] s) x [] bits simp only [pairRegisters,update_regs_zero,update_regs_one,List.append_nil] at h₁ have h₂ := runs_strip (k:=1) 1 O (regs [] [] [] s) x.reverse (fun i => bits (2*x.length+1+i)) simp only [update_regs_one] at h₂ have h₃ := runs_reverse (k:=1) 1 0 (by decide) O (regs [] [] [] s) (stripZeros x.reverse) [] (fun i => bits (2*x.length+1+(stripCost x.reverse+i))) simp only [pairRegisters,update_regs_zero,update_regs_one,List.append_nil] at h₃ simpa only [normalCode,normalCost,normalWord,Nat.zero_add] using runs_seq O bits h₁ (runs_seq O _ h₂ h₃) lemma bounded_normalCode {n : ℕ} (O : IndependenceOracle n) (x : Word) : Bounded normalCode O x (binaryValue x).bits (5*x.length+4) := by refine ⟨normalCost x,0,normalCost x,normalCost_le x,Nat.zero_le _,normalCost_le x,?_⟩ rw [←normalWord_eq_bits] exact computes_normalCode O x def addBlock : Block 1 := ⟨16,addProgram 0 1 2,rfl⟩ def addTime (x y : Word) : ℕ := addCost false x y+2*(addDigits false x y).length+1 lemma runs_add {n : ℕ} (O : IndependenceOracle n) (x y s : Word) (bits : ℕ → Bool) : Runs addBlock O bits (regs x y [] s) (regs (addDigits false x y) [] [] s) (addTime x y) 0 (addTime x y) := by dsimp only [Runs,addBlock] intro q w have h := (addition_block (k:=1) 0 1 2 (by decide) (by decide) (by decide) O (regs [] [] [] s) x y q w bits).2.2 convert h using 1 <;> simp only [addTime,addConfig,state,tripleRegisters,pairRegisters,update_regs_zero, update_regs_one,update_regs_two,lastLabel,Nat.add_zero] rfl lemma addTime_le (x y : Word) : addTime x y ≤ 5*(x.length+y.length)+6 := by have h := addDigits_length_cost false x y unfold addTime omega def addCode : Block 1 := seq (unpack 0 1) (seq addBlock normalCode) lemma computes_add {n : ℕ} (O : IndependenceOracle n) (x y : Word) : Computes addCode O (pair x y) (binaryValue x+binaryValue y).bits (3*x.length+1+addTime y x+normalCost (addDigits false y x)) 0 (3*x.length+1+addTime y x+normalCost (addDigits false y x)) := by have hv : binaryValue (addDigits false y x)=binaryValue x+binaryValue y := by simpa [Nat.add_comm] using addDigits_value false y x intro s bits have hs := split_pair O x y [] s bits simp only [List.append_nil] at hs have ha := runs_add O y x s (fun i => bits (3*x.length+1+i)) have hn := computes_normalCode O (addDigits false y x) s (fun i => bits (3*x.length+1+(addTime y x+i))) rw [normalWord_eq_bits,hv] at hn have ht := runs_seq O bits hs (runs_seq O _ ha hn) simpa only [addCode,Nat.zero_add,Nat.add_assoc] using ht lemma bounded_add {n : ℕ} (O : IndependenceOracle n) (x y : Word) : Bounded addCode O (pair x y) (binaryValue x+binaryValue y).bits (20*(x.length+y.length+1)) := by have h₁ := addTime_le y x have h₂ := normalCost_le (addDigits false y x) have h₃ := (addDigits_length_cost false y x).1 refine ⟨_,0,_,?_,Nat.zero_le _,?_,computes_add O x y⟩ <;> omega def mulBlock : Block 1 := ⟨26,mulProgram,rfl⟩ lemma mulRegisters_regs (x y z s : Word) : mulRegisters (regs [] [] [] s) x y z []=regs x y z s := by funext i; fin_cases i <;> simp [mulRegisters,regs] lemma runs_mul {n : ℕ} (O : IndependenceOracle n) (x y s : Word) (bits : ℕ → Bool) : Runs mulBlock O bits (regs x y [] s) (regs (List.replicate y.length false++x) [] (mulDigits x y []) s) (mulCost x y []) 0 (mulCost x y []) := by dsimp only [Runs,mulBlock] intro q w have h := (multiplication_block (k:=1) O (regs [] [] [] s) x y q w bits).2.2 convert h using 1 <;> simp only [mulConfig,state,mulRegisters_regs,lastLabel,Nat.add_zero] rfl lemma clear_zero {n : ℕ} (O : IndependenceOracle n) (x y z s : Word) (bits : ℕ → Bool) : Runs (clear 0) O bits (regs x y z s) (regs [] y z s) (x.length+1) 0 (x.length+1) := by simpa only [update_regs_zero] using runs_clear (k:=1) 0 O (regs [] y z s) x bits lemma move_two_zero {n : ℕ} (O : IndependenceOracle n) (x s : Word) (bits : ℕ → Bool) : Runs (move 2 1 0) O bits (regs [] [] x s) (regs x [] [] s) (4*x.length+2) 0 (4*x.length+2) := by simpa only [tripleRegisters,pairRegisters,update_regs_zero,update_regs_one,update_regs_two,List.append_nil] using runs_move (k:=1) 2 1 0 (by decide) (by decide) (by decide) O (regs [] [] [] s) x [] bits def mulCode : Block 1 := seq (unpack 0 1) (seq mulBlock (seq (clear 0) (seq (move 2 1 0) normalCode))) def mulTime (x y : Word) : ℕ := 3*x.length+1+mulCost y x []+(x.length+y.length+1)+(4*(mulDigits y x []).length+2)+normalCost (mulDigits y x []) lemma computes_mul {n : ℕ} (O : IndependenceOracle n) (x y : Word) : Computes mulCode O (pair x y) (binaryValue x*binaryValue y).bits (mulTime x y) 0 (mulTime x y) := by have hv : binaryValue (mulDigits y x [])=binaryValue x*binaryValue y := by simp [mulDigits_value,binaryValue,Nat.mul_comm] intro s bits have h₁ := split_pair O x y [] s bits simp only [List.append_nil] at h₁ have h₂ := runs_mul O y x s (fun i => bits (3*x.length+1+i)) have h₃ := clear_zero O (List.replicate x.length false++y) [] (mulDigits y x []) s (fun i => bits (3*x.length+1+(mulCost y x []+i))) simp only [List.length_append,List.length_replicate] at h₃ have h₄ := move_two_zero O (mulDigits y x []) s (fun i => bits (3*x.length+1+(mulCost y x []+(x.length+y.length+1+i)))) have h₅ := computes_normalCode O (mulDigits y x []) s (fun i => bits (3*x.length+1+(mulCost y x []+(x.length+y.length+1+(4*(mulDigits y x []).length+2+i))))) rw [normalWord_eq_bits,hv] at h₅ have ht := runs_seq O bits h₁ (runs_seq O _ h₂ (runs_seq O _ h₃ (runs_seq O _ h₄ h₅))) simpa only [mulCode,mulTime,Nat.zero_add,Nat.add_assoc] using ht lemma mulTime_le (x y : Word) : mulTime x y ≤ 60*(x.length+y.length+1)^2 := by have h₁ := mulCost_bound y x [] have h₂ := mulDigits_length y x [] have h₃ := normalCost_le (mulDigits y x []) simp only [List.length_nil,Nat.max_zero] at h₁ h₂ unfold mulTime nlinarith [sq_nonneg (x.length:ℤ),sq_nonneg (y.length:ℤ)] lemma bounded_mul {n : ℕ} (O : IndependenceOracle n) (x y : Word) : Bounded mulCode O (pair x y) (binaryValue x*binaryValue y).bits (60*(x.length+y.length+1)^2) := ⟨_,0,_,mulTime_le x y,Nat.zero_le _,mulTime_le x y,computes_mul O x y⟩ lemma computes_parallel {n : ℕ} {O : IndependenceOracle n} {p q : Block 1} {x y u v : Word} {t₁ q₁ w₁ t₂ q₂ w₂ : ℕ} (hp : Computes p O x u t₁ q₁ w₁) (hq : Computes q O y v t₂ q₂ w₂) : Computes (parallel p q) O (pair x y) (pair u v) (7*x.length+28*y.length+39*u.length+18*v.length+46+t₁+t₂) (q₁+q₂) (7*x.length+28*y.length+39*u.length+18*v.length+46+w₁+w₂) := by have ht := computes_seq (computes_left hp y) (computes_right hq u) convert ht using 1 <;> first | rfl | omega lemma computes_fanout {n : ℕ} {O : IndependenceOracle n} {p q : Block 1} {x u v : Word} {t₁ q₁ w₁ t₂ q₂ w₂ : ℕ} (hp : Computes p O x u t₁ q₁ w₁) (hq : Computes q O x v t₂ q₂ w₂) : Computes (fanout p q) O x (pair u v) (43*x.length+39*u.length+18*v.length+50+t₁+t₂) (q₁+q₂) (43*x.length+39*u.length+18*v.length+50+w₁+w₂) := by have ht := computes_seq (computes_duplicate O x) (computes_parallel hp hq) convert ht using 1 <;> first | rfl | omega def prependCode : Word → Block 1 | [] => skip 1 | b::xs => seq (prependCode xs) (push 0 b) lemma computes_prepend {n : ℕ} (O : IndependenceOracle n) (x y : Word) : Computes (prependCode x) O y (x++y) x.length 0 x.length := by induction x with | nil => exact computes_skip O y | cons b xs ih => have hp : Computes (push 0 b) O (xs++y) (b::(xs++y)) 1 0 1 := by intro s bits simpa only [regs_zero,update_regs_zero] using runs_push O bits (regs (xs++y) [] [] s) 0 b have ht := computes_seq ih hp simpa only [prependCode,List.cons_append,List.length_cons,Nat.zero_add] using ht def constCode (x : Word) : Block 1 := seq (clear 0) (prependCode x) lemma computes_const {n : ℕ} (O : IndependenceOracle n) (x y : Word) : Computes (constCode y) O x y (x.length+y.length+1) 0 (x.length+y.length+1) := by have hc : Computes (clear 0) O x [] (x.length+1) 0 (x.length+1) := fun s bits => clear_zero O x [] [] s bits have ht := computes_seq hc (computes_prepend O y []) simpa only [constCode,List.append_nil,Nat.zero_add,show x.length+1+y.length=x.length+y.length+1 by omega] using ht def selectCode (p q : Block 1) : Block 1 := seq (unpack 0 1) (fork (.pop 1 false false true) p q) lemma computes_select {n : ℕ} {O : IndependenceOracle n} (p q : Block 1) (b : Bool) {x y : Word} {t a w : ℕ} (h : Computes (if b then q else p) O x y t a w) : Computes (selectCode p q) O (pair [b] x) y (5+t) a (5+w) := by intro s bits have hu := split_pair O [b] x [] s bits simp only [List.append_nil,List.length_singleton,show 3*1+1=4 by omega] at hu have hf : Runs (fork (.pop 1 false false true) p q) O (fun i => bits (4+i)) (regs x [b] [] s) (regs y [] [] s) (1+t) a (1+w) := by cases b with | false => have hp := h s (fun i => bits (4+(1+i))) have hh := fork_run_no (.pop 1 false false true) p q O (fun i => bits (4+i)) (R:=regs x [false] [] s) (by simp [Test.result]) hp simpa only [Test.queries,Test.work,Nat.zero_add] using hh | true => have hp := h s (fun i => bits (4+(1+i))) have hh := fork_run_yes (.pop 1 false false true) p q O (fun i => bits (4+i)) (R:=regs x [true] [] s) (by simp [Test.result]) hp simpa only [Test.queries,Test.work,Nat.zero_add] using hh have ht := runs_seq O bits hu hf simpa only [selectCode,Nat.zero_add,show 4+(1+t)=5+t by omega,show 4+(1+w)=5+w by omega] using ht def queryCode (which : Bool) : Block 1 := fork (.query which 0) (constCode [false]) (constCode [true]) lemma computes_query {n : ℕ} (O : IndependenceOracle n) (which : Bool) (x : Word) (hx : x.length=n) : Computes (queryCode which) O x [O which (fun i => x[i.val]?.getD false)] (n+3) 1 (3*n+3) := by intro s bits have hp (b : Bool) := computes_const O x [b] s (fun i => bits (1+i)) have hres : (Test.query which 0).result O (bits 0) (regs x [] [] s)= some (O which (fun i => x[i.val]?.getD false),regs x [] [] s) := by simp [Test.result,hx] cases hb : O which (fun i => x[i.val]?.getD false) with | false => rw [hb] at hres have ht := fork_run_no (.query which 0) (constCode [false]) (constCode [true]) O bits hres (hp false) simp only [Test.queries,Test.work,regs_zero,hx,List.length_singleton] at ht convert ht using 1 <;> first | rfl | omega | true => rw [hb] at hres have ht := fork_run_yes (.query which 0) (constCode [false]) (constCode [true]) O bits hres (hp true) simp only [Test.queries,Test.work,regs_zero,hx,List.length_singleton] at ht convert ht using 1 <;> first | rfl | omega def quadRegs (x y z u s : Word) : Registers 1 := Function.update (regs x y z s) 3 u @[simp] lemma quadRegs_zero (x y z u s : Word) : quadRegs x y z u s 0=x := by simp [quadRegs] @[simp] lemma quadRegs_one (x y z u s : Word) : quadRegs x y z u s 1=y := by simp [quadRegs] @[simp] lemma quadRegs_two (x y z u s : Word) : quadRegs x y z u s 2=z := by simp [quadRegs] @[simp] lemma quadRegs_three (x y z u s : Word) : quadRegs x y z u s 3=u := by simp [quadRegs] @[simp] lemma quadRegs_nil (x y z s : Word) : quadRegs x y z [] s=regs x y z s := by funext i; fin_cases i <;> simp [quadRegs,regs] @[simp] lemma update_quad_zero (x y z u s v : Word) : Function.update (quadRegs x y z u s) 0 v=quadRegs v y z u s := by funext i; fin_cases i <;> simp [quadRegs,regs] @[simp] lemma update_quad_one (x y z u s v : Word) : Function.update (quadRegs x y z u s) 1 v=quadRegs x v z u s := by funext i; fin_cases i <;> simp [quadRegs,regs] @[simp] lemma update_quad_two (x y z u s v : Word) : Function.update (quadRegs x y z u s) 2 v=quadRegs x y v u s := by funext i; fin_cases i <;> simp [quadRegs,regs] @[simp] lemma update_quad_three (x y z u s v : Word) : Function.update (quadRegs x y z u s) 3 v=quadRegs x y z v s := by simp [quadRegs] lemma divRegisters_quad (x y z u s : Word) : divRegisters (regs [] [] [] s) x y z u [] []=quadRegs x y z u s := by funext i; fin_cases i <;> simp [divRegisters,quadRegs,regs] def divBlock : Block 1 := ⟨53,divisionProgram,rfl⟩ lemma runs_div {n : ℕ} (O : IndependenceOracle n) (x y s : Word) (bits : ℕ → Bool) : Runs divBlock O bits (regs x y [] s) (quadRegs [] y (divisionWords x y [] []).1 (divisionWords x y [] []).2 s) (divisionCost x y []) 0 (divisionCost x y []) := by dsimp only [Runs,divBlock] intro q w have h := division_machine_run (k:=1) O (regs [] [] [] s) x y [] [] q w bits convert h using 1 <;> simp only [divisionConfig,state,divRegisters_quad,quadRegs_nil,lastLabel,Nat.add_zero] rfl lemma div_prepare {n : ℕ} (O : IndependenceOracle n) (x y s : Word) (bits : ℕ → Bool) : Runs (seq (reverse 0 2) (move 2 3 0)) O bits (regs x y [] s) (regs x.reverse y [] s) (6*x.length+3) 0 (6*x.length+3) := by have hr := runs_reverse (k:=1) 0 2 (by decide) O (regs [] y [] s) x [] bits simp only [pairRegisters,update_regs_zero,update_regs_two,List.append_nil] at hr have hm := runs_move (k:=1) 2 3 0 (by decide) (by decide) (by decide) O (quadRegs [] y [] [] s) x.reverse [] (fun i => bits (2*x.length+1+i)) simp only [tripleRegisters,pairRegisters,update_quad_zero,update_quad_two,update_quad_three, List.append_nil,List.length_reverse] at hm simp only [quadRegs_nil] at hm have ht := runs_seq O bits hr hm convert ht using 1 <;> first | rfl | omega lemma div_finish {n : ℕ} (O : IndependenceOracle n) (x r q s : Word) (bits : ℕ → Bool) : Runs (seq (clear 1) (seq (pack 2 3) (move 3 1 0))) O bits (quadRegs [] x r q s) (regs (pair r q) [] [] s) (x.length+11*r.length+4*q.length+9) 0 (x.length+11*r.length+4*q.length+9) := by have h₁ := runs_clear (k:=1) 1 O (quadRegs [] [] r q s) x bits simp only [update_quad_one] at h₁ have h₂ := runs_pack (k:=1) 2 3 (by decide) O (quadRegs [] [] [] [] s) r q (fun i => bits (x.length+1+i)) simp only [pairRegisters,update_quad_two,update_quad_three] at h₂ change Runs (pack 2 3) O _ (quadRegs [] [] r q s) (quadRegs [] [] [] (pair r q) s) _ _ _ at h₂ have h₃ := runs_move (k:=1) 3 1 0 (by decide) (by decide) (by decide) O (quadRegs [] [] [] [] s) (pair r q) [] (fun i => bits (x.length+1+(3*r.length+2+i))) simp only [tripleRegisters,pairRegisters,update_quad_zero,update_quad_one,update_quad_three, List.append_nil] at h₃ simp only [quadRegs_nil] at h₃ have ht := runs_seq O bits h₁ (runs_seq O _ h₂ h₃) convert ht using 1 <;> first | rfl | simp only [pair_length]; omega def rawDivCode : Block 1 := seq (unpack 0 1) (seq (seq (reverse 0 2) (move 2 3 0)) (seq divBlock (seq (clear 1) (seq (pack 2 3) (move 3 1 0))))) def divResult (x y : Word) : Word × Word := divisionWords y.reverse x [] [] def rawDivTime (x y : Word) : ℕ := 4*x.length+6*y.length+11*(divResult x y).1.length+4*(divResult x y).2.length+13+divisionCost y.reverse x [] lemma computes_rawDiv {n : ℕ} (O : IndependenceOracle n) (x y : Word) : Computes rawDivCode O (pair x y) (pair (divResult x y).1 (divResult x y).2) (rawDivTime x y) 0 (rawDivTime x y) := by intro s bits have h₁ := split_pair O x y [] s bits simp only [List.append_nil] at h₁ have h₂ := div_prepare O y x s (fun i => bits (3*x.length+1+i)) have h₃ := runs_div O y.reverse x s (fun i => bits (3*x.length+1+(6*y.length+3+i))) have h₄ := div_finish O x (divResult x y).1 (divResult x y).2 s (fun i => bits (3*x.length+1+(6*y.length+3+(divisionCost y.reverse x []+i)))) have ht := runs_seq O bits h₁ (runs_seq O _ h₂ (runs_seq O _ h₃ h₄)) convert ht using 1 <;> first | rfl | unfold rawDivTime; omega lemma divisionWords_length (xs ys zs ws : Word) : (divisionWords xs ys zs ws).1.length ≤ max ys.length zs.length+xs.length ∧ (divisionWords xs ys zs ws).2.length = xs.length+ws.length := by induction xs generalizing zs ws with | nil => simp only [divisionWords,List.length_nil,Nat.add_zero,Nat.zero_add]; exact ⟨Nat.le_max_right _ _,True.intro⟩ | cons x xs ih => have hh := ih (divisionRemainder ys (x::zs)) (divisionDigit ys (x::zs)::ws) have hr := divisionRemainder_length ys (x::zs) simp only [divisionWords,List.length_cons] at * constructor <;> omega lemma divResult_length (x y : Word) : (divResult x y).1.length ≤ x.length+y.length ∧ (divResult x y).2.length=y.length := by simpa only [divResult,List.length_reverse,List.length_nil,Nat.max_zero,Nat.add_zero] using divisionWords_length y.reverse x [] [] lemma rawDivTime_le (x y : Word) : rawDivTime x y ≤ 100*(x.length+y.length+1)^2 := by have hd := divisionCost_bound y.reverse x [] x.length le_rfl (by simp) have hl := divResult_length x y simp only [List.length_reverse] at hd unfold rawDivTime nlinarith def divCode : Block 1 := seq rawDivCode (parallel normalCode normalCode) def normalizedResult (x y : Word) : Word := pair (binaryValue (divResult x y).1).bits (binaryValue (divResult x y).2).bits lemma bounded_div {n : ℕ} (O : IndependenceOracle n) (x y : Word) : Bounded divCode O (pair x y) (normalizedResult x y) (300*(x.length+y.length+1)^2) := by have h₁ := computes_rawDiv O x y have h₂ := computes_parallel (computes_normalCode O (divResult x y).1) (computes_normalCode O (divResult x y).2) have ht := computes_seq h₁ h₂ simp only [normalWord_eq_bits] at ht have hl := divResult_length x y have hr := rawDivTime_le x y have hn₁ := normal_length (divResult x y).1 have hn₂ := normal_length (divResult x y).2 have hc₁ := normalCost_le (divResult x y).1 have hc₂ := normalCost_le (divResult x y).2 rw [normalWord_eq_bits] at hn₁ hn₂ refine ⟨_,0,_,?_,Nat.zero_le _,?_,ht⟩ <;> nlinarith lemma normalizedResult_pos (x y : Word) (hx : 0 < binaryValue x) : normalizedResult x y=pair (binaryValue y%binaryValue x).bits (binaryValue y/binaryValue x).bits := by have hh := divisionWords_correct y.reverse x hx simpa only [normalizedResult,divResult,List.reverse_reverse] using congrArg₂ (fun a b : ℕ => pair a.bits b.bits) hh.1 hh.2 def cmpLabel (i : Fin 10) : Fin 11 := ⟨i.val,by omega⟩ def cmpBlock : Block 1 where size := 10 code := fun pc => if h : pc.val < 8 then (compareProgram (1 : Fin 9) 0 ⟨pc.val,by omega⟩).relabel cmpLabel else if pc.val=8 then .push 0 false 10 else if pc.val=9 then .push 0 true 10 else .halt exit_halt := rfl lemma cmpBlock_body (i : Fin 10) (h : compareProgram (1 : Fin 9) 0 i ≠ .halt) : cmpBlock.code (cmpLabel i)=(compareProgram (1 : Fin 9) 0 i).relabel cmpLabel := by have hi : i.val<8 := by by_contra hn have hiv := i.isLt have : i.val=8 ∨ i.val=9 := by omega rcases this with hi|hi <;> simp [compareProgram,hi] at h simp [cmpBlock,cmpLabel,hi] lemma runs_cmp {n : ℕ} (O : IndependenceOracle n) (x y s : Word) (bits : ℕ → Bool) : Runs cmpBlock O bits (regs y x [] s) (regs [decide (binaryValue x simp [h,relabelConfig,cmpLabel,compareConfig,state,execution,machineStep,cmpBlock,lastLabel,Nat.add_assoc] def cmpCode : Block 1 := seq (unpack 0 1) cmpBlock lemma computes_cmp {n : ℕ} (O : IndependenceOracle n) (x y : Word) : Computes cmpCode O (pair x y) [decide (binaryValue x bits (3*x.length+1+i)) have hh := runs_seq O bits hu hr convert hh using 1 <;> first | rfl | omega lemma bounded_cmp {n : ℕ} (O : IndependenceOracle n) (x y : Word) : Bounded cmpCode O (pair x y) [decide (binaryValue x omega def loopAccum {A : Type*} (f : A → A) (g : A → ℕ → ℕ) : ℕ → A → ℕ | 0,_ => 0 | m+1,x => g x m+loopAccum f g m (f x) theorem runs_repeat {k n : ℕ} {A : Type*} (p : Block k) (a : Fin (k+8)) (O : IndependenceOracle n) (encode : A → Registers k) (f : A → A) (ticks queries work : A → ℕ → ℕ) (body : ∀ v xs bits, Runs p O bits (Function.update (encode v) a xs) (Function.update (encode (f v)) a xs) (ticks v xs.length) (queries v xs.length) (work v xs.length)) (v : A) (xs : Word) (bits : ℕ → Bool) : Runs (repeatBlock p a) O bits (Function.update (encode v) a xs) (Function.update (encode (loopState f xs.length v)) a []) (xs.length+loopAccum f ticks xs.length v+1) (loopAccum f queries xs.length v) (xs.length+loopAccum f work xs.length v+1) := by dsimp only [Runs, repeatBlock] intro q c induction xs generalizing v q c bits with | nil => have h := repeatProgram_empty p.code a O (encode v) q c bits simpa [Runs,repeatBlock,state,loopConfig,loopAccum,loopState] using h | cons x xs ih => have hb := body v xs (fun i => bits (1+i)) q (c+1) have hnone : (execution p.code O (state (Function.update (encode v) a xs) 0 q (c+1)) (fun i => bits (1+i)) (ticks v xs.length)).output=none := by rw [hb]; rfl have hl := execution_relabel_before_halt p.code (repeatProgram p.code a) (loopLabel p.size) (lastLabel p.size) p.exit_halt (repeatProgram_body p.code a) O _ (fun i => bits (1+i)) (ticks v xs.length) hnone have hfirst : execution (repeatProgram p.code a) O (state (Function.update (encode v) a (x::xs)) 0 q c) bits (1+ticks v xs.length)= state (Function.update (encode (f v)) a xs) 0 (q+queries v xs.length) (c+1+work v xs.length) := by rw [execution_add] change execution _ O (execution (repeatProgram p.code a) O (loopConfig (Function.update (encode v) a (x::xs)) 0 q c) bits 1) _ _ = _ rw [repeatProgram_pop] change execution _ O (relabelConfig _ (state (Function.update (encode v) a xs) 0 q (c+1))) _ _ = _ rw [hl,hb] simp [relabelConfig,state,loopLabel_last] simp only [List.length_cons,loopAccum,loopState] rw [show xs.length+1+(ticks v xs.length+loopAccum f ticks xs.length (f v))+1= (1+ticks v xs.length)+(xs.length+loopAccum f ticks xs.length (f v)+1) by omega, execution_add,hfirst] have hi := ih (f v) (fun i => bits (1+ticks v xs.length+i)) (q+queries v xs.length) (c+1+work v xs.length) change execution (repeatProgram p.code a) O _ _ _ = _ at hi rw [hi] congr 1 <;> omega lemma loopAccum_le {A : Type*} (f : A → A) (g : A → ℕ → ℕ) (m B : ℕ) (h : ∀ x i, i < m → g x i ≤ B) (x : A) : loopAccum f g m x ≤ m * B := by induction m generalizing x with | zero => simp [loopAccum] | succ m ih => have h₁ := h x m (by omega) have h₂ := ih (fun x i hi => h x i (by omega)) (f x) simpa only [loopAccum,Nat.succ_mul] using Nat.add_le_add h₁ h₂ |>.trans (by omega) lemma save_one {n : ℕ} (O : IndependenceOracle n) (x y s : Word) (bits : ℕ → Bool) : Runs (pack 1 8) O bits (regs x y [] s) (regs x [] [] (pair y s)) (3*y.length+2) 0 (3*y.length+2) := by simpa only [pair,pairRegisters,update_regs_one,update_regs_eight] using runs_pack (k:=1) 1 8 (by decide) O (regs x [] [] []) y s bits def iterationBody (p : Block 1) : Block 1 := seq (pack 1 8) (seq p (unpack 8 1)) lemma iteration_body {n : ℕ} {O : IndependenceOracle n} {p : Block 1} {x y : Word} {t q w : ℕ} (h : Computes p O x y t q w) (counter saved : Word) (bits : ℕ → Bool) : Runs (iterationBody p) O bits (regs x counter [] saved) (regs y counter [] saved) (6*counter.length+3+t) q (6*counter.length+3+w) := by have hs := save_one O x counter saved bits have hp := h (pair counter saved) (fun i => bits (3*counter.length+2+i)) have hr := restore_one O y counter saved (fun i => bits (3*counter.length+2+(t+i))) have ht := runs_seq O bits hs (runs_seq O _ hp hr) convert ht using 1 <;> first | rfl | omega def iterateCode (p : Block 1) : Block 1 := seq (unpack 0 1) (repeatBlock (iterationBody p) 1) lemma computes_iterate {n : ℕ} {A : Type*} (O : IndependenceOracle n) (p : Block 1) (encode : A → Word) (f : A → A) (t q w : A → ℕ) (h : ∀ x, Computes p O (encode x) (encode (f x)) (t x) (q x) (w x)) (x : A) (counter : Word) : Computes (iterateCode p) O (pair counter (encode x)) (encode (loopState f counter.length x)) (4*counter.length+loopAccum f (fun x i => 6*i+3+t x) counter.length x+2) (loopAccum f (fun x _ => q x) counter.length x) (4*counter.length+loopAccum f (fun x i => 6*i+3+w x) counter.length x+2) := by intro saved bits have hs := split_pair O counter (encode x) [] saved bits simp only [List.append_nil] at hs have hr := runs_repeat (iterationBody p) 1 O (fun x => regs (encode x) [] [] saved) f (fun x i => 6*i+3+t x) (fun x _ => q x) (fun x i => 6*i+3+w x) (by intro x xs bits; simpa only [update_regs_one] using iteration_body (h x) xs saved bits) x counter (fun i => bits (3*counter.length+1+i)) simp only [update_regs_one] at hr have ht := runs_seq O bits hs hr convert ht using 1 <;> first | rfl | omega lemma bounded_iterate {n : ℕ} {A : Type*} (O : IndependenceOracle n) (p : Block 1) (encode : A → Word) (f : A → A) (B : ℕ) (h : ∀x,Bounded p O (encode x) (encode (f x)) B) (x : A) (counter : Word) : Bounded (iterateCode p) O (pair counter (encode x)) (encode (loopState f counter.length x)) (counter.length*(6*counter.length+B+7)+2) := by classical choose t q w ht hq hw hc using h have hc' := computes_iterate O p encode f t q w hc x counter have ht' := loopAccum_le f (fun x i => 6*i+3+t x) counter.length (6*counter.length+3+B) (by intro x i hi; have := ht x; omega) x have hw' := loopAccum_le f (fun x i => 6*i+3+w x) counter.length (6*counter.length+3+B) (by intro x i hi; have := hw x; omega) x have hq' := loopAccum_le f (fun x _ => q x) counter.length B (by intro x _ _; exact hq x) x refine ⟨_,_,_,?_,?_,?_,hc'⟩ <;> nlinarith def words : List Word → Word | [] => [] | x::xs => true :: pair x (words xs) lemma words_length (xs : List Word) : (words xs).length = 2*(xs.map List.length).sum+2*xs.length := by induction xs with | nil => rfl | cons x xs ih => simp only [words,List.length_cons,pair_length,List.map_cons,List.sum_cons,ih]; omega def foldWords {A X : Type*} (f : X → A → A) : List X → A → A | [],s => s | x::xs,s => foldWords f xs (f x s) def foldCharge {A X : Type*} (f : X → A → A) (g : X → List X → A → ℕ) : List X → A → ℕ | [],_ => 0 | x::xs,s => g x xs s+foldCharge f g xs (f x s) lemma runs_repeat_cons {k n : ℕ} {p : Block k} {a : Fin (k+8)} {O : IndependenceOracle n} {bits : ℕ → Bool} {R R' R'' : Registers k} {b : Bool} {xs : Word} {t q w u v z : ℕ} (hp : Runs p O (fun i => bits (1+i)) (Function.update R a xs) R' t q w) (hi : Runs (repeatBlock p a) O (fun i => bits (1+t+i)) R' R'' u v z) : Runs (repeatBlock p a) O bits (Function.update R a (b::xs)) R'' (1+t+u) (q+v) (1+w+z) := by dsimp only [Runs, repeatBlock] at * intro q₀ w₀ have hb := hp q₀ (w₀+1) have hnone : (execution p.code O (state (Function.update R a xs) 0 q₀ (w₀+1)) (fun i => bits (1+i)) t).output=none := by rw [hb]; rfl have hl := execution_relabel_before_halt p.code (repeatProgram p.code a) (loopLabel p.size) (lastLabel p.size) p.exit_halt (repeatProgram_body p.code a) O _ (fun i => bits (1+i)) t hnone rw [execution_add,execution_add] change execution _ O (execution _ O (execution (repeatProgram p.code a) O (loopConfig (Function.update R a (b::xs)) 0 q₀ w₀) bits 1) _ _) _ _ = _ rw [repeatProgram_pop] change execution _ O (execution _ O (relabelConfig _ (state (Function.update R a xs) 0 q₀ (w₀+1))) _ _) _ _ = _ rw [hl,hb] simp only [relabelConfig,state,loopLabel_last] have hh := hi (q₀+q) (w₀+1+w) simpa [state,Nat.add_assoc] using hh lemma unpack_one_two {n : ℕ} (O : IndependenceOracle n) (a x tail s : Word) (bits : ℕ → Bool) : Runs (unpack 1 2) O bits (regs a (pair x tail) [] s) (regs a tail x s) (3*x.length+1) 0 (3*x.length+1) := by simpa only [pair,pairRegisters,update_regs_one,update_regs_two] using runs_unpack_packed (k:=1) 1 2 (by decide) O (regs a [] [] s) x tail bits lemma pack_two_zero {n : ℕ} (O : IndependenceOracle n) (a x s : Word) (bits : ℕ → Bool) : Runs (pack 2 0) O bits (regs a [] x s) (regs (pair x a) [] [] s) (3*x.length+2) 0 (3*x.length+2) := by simpa only [pair,pairRegisters,update_regs_zero,update_regs_two] using runs_pack (k:=1) 2 0 (by decide) O (regs [] [] [] s) x a bits lemma save_one_with_two {n : ℕ} (O : IndependenceOracle n) (a y x s : Word) (bits : ℕ → Bool) : Runs (pack 1 8) O bits (regs a y x s) (regs a [] x (pair y s)) (3*y.length+2) 0 (3*y.length+2) := by simpa only [pair,pairRegisters,update_regs_one,update_regs_eight] using runs_pack (k:=1) 1 8 (by decide) O (regs a [] x []) y s bits def listBody (p : Block 1) : Block 1 := seq (unpack 1 2) (seq (pack 1 8) (seq (pack 2 0) (seq p (unpack 8 1)))) lemma list_body {n : ℕ} {O : IndependenceOracle n} {p : Block 1} {x a b : Word} {t q w : ℕ} (h : Computes p O (pair x a) b t q w) (tail saved : Word) (bits : ℕ → Bool) : Runs (listBody p) O bits (regs a (pair x tail) [] saved) (regs b tail [] saved) (6*x.length+6*tail.length+6+t) q (6*x.length+6*tail.length+6+w) := by have h₁ := unpack_one_two O a x tail saved bits have h₂ := save_one_with_two O a tail x saved (fun i => bits (3*x.length+1+i)) have h₃ := pack_two_zero O a x (pair tail saved) (fun i => bits (3*x.length+1+(3*tail.length+2+i))) have h₄ := h (pair tail saved) (fun i => bits (3*x.length+1+(3*tail.length+2+(3*x.length+2+i)))) have h₅ := restore_one O b tail saved (fun i => bits (3*x.length+1+(3*tail.length+2+(3*x.length+2+(t+i))))) have ht := runs_seq O bits h₁ (runs_seq O _ h₂ (runs_seq O _ h₃ (runs_seq O _ h₄ h₅))) convert ht using 1 <;> first | rfl | omega lemma list_loop {n : ℕ} {A X : Type*} (O : IndependenceOracle n) (p : Block 1) (encode : A → Word) (encX : X → Word) (f : X → A → A) (t q w : X → A → ℕ) (h : ∀ x a, Computes p O (pair (encX x) (encode a)) (encode (f x a)) (t x a) (q x a) (w x a)) (xs : List X) (a : A) (saved : Word) (bits : ℕ → Bool) : Runs (repeatBlock (listBody p) 1) O bits (regs (encode a) (words (xs.map encX)) [] saved) (regs (encode (foldWords f xs a)) [] [] saved) (1+foldCharge f (fun x tail a => 7+6*(encX x).length+6*(words (tail.map encX)).length+t x a) xs a) (foldCharge f (fun x _ a => q x a) xs a) (1+foldCharge f (fun x tail a => 7+6*(encX x).length+6*(words (tail.map encX)).length+w x a) xs a) := by induction xs generalizing a bits with | nil => dsimp only [Runs, repeatBlock] intro q₀ w₀ simpa only [repeatBlock,state,loopConfig,words,List.map_nil,foldWords,foldCharge,Nat.add_zero, update_regs_one] using repeatProgram_empty (listBody p).code 1 O (regs (encode a) [] [] saved) q₀ w₀ bits | cons x xs ih => have hb := list_body (h x a) (words (xs.map encX)) saved (fun i => bits (1+i)) have hr := runs_repeat_cons (R:=regs (encode a) [] [] saved) (b:=true) (by simpa only [update_regs_one] using hb) (ih (f x a) (fun i => bits (1+(6*(encX x).length+6*(words (xs.map encX)).length+6+t x a)+i))) simp only [update_regs_one] at hr convert hr using 1 <;> first | rfl | simp only [foldCharge]; omega def foldCode (p : Block 1) : Block 1 := seq (unpack 0 1) (repeatBlock (listBody p) 1) lemma computes_fold {n : ℕ} {A X : Type*} (O : IndependenceOracle n) (p : Block 1) (encode : A → Word) (encX : X → Word) (f : X → A → A) (t q w : X → A → ℕ) (h : ∀ x a, Computes p O (pair (encX x) (encode a)) (encode (f x a)) (t x a) (q x a) (w x a)) (xs : List X) (a : A) : Computes (foldCode p) O (pair (words (xs.map encX)) (encode a)) (encode (foldWords f xs a)) (3*(words (xs.map encX)).length+2+foldCharge f (fun x tail a => 7+6*(encX x).length+6*(words (tail.map encX)).length+t x a) xs a) (foldCharge f (fun x _ a => q x a) xs a) (3*(words (xs.map encX)).length+2+foldCharge f (fun x tail a => 7+6*(encX x).length+6*(words (tail.map encX)).length+w x a) xs a) := by intro saved bits have hs := split_pair O (words (xs.map encX)) (encode a) [] saved bits simp only [List.append_nil] at hs have hl := list_loop O p encode encX f t q w h xs a saved (fun i => bits (3*(words (xs.map encX)).length+1+i)) have ht := runs_seq O bits hs hl convert ht using 1 <;> first | rfl | omega def reverseCode : Block 1 := seq (reverse 0 1) (move 1 2 0) lemma computes_reverse {n : ℕ} (O : IndependenceOracle n) (x : Word) : Computes reverseCode O x x.reverse (6*x.length+3) 0 (6*x.length+3) := by intro s bits have hr := runs_reverse (k:=1) 0 1 (by decide) O (regs [] [] [] s) x [] bits simp only [pairRegisters,update_regs_zero,update_regs_one,List.append_nil] at hr have hm := move_one_zero O x.reverse [] s (fun i => bits (2*x.length+1+i)) have ht := runs_seq O bits hr hm simpa only [reverseCode,List.append_nil,List.length_reverse,Nat.zero_add, show 2*x.length+1+(4*x.length+2)=6*x.length+3 by omega] using ht def boolListBlock : Block 1 where size := 7 code := fun pc => match pc.val with | 0 => .pop 1 7 1 2 | 1 => .push 0 true 3 | 2 => .push 0 true 4 | 3 => .push 0 false 5 | 4 => .push 0 true 5 | 5 => .push 0 false 6 | 6 => .push 0 true 0 | _ => .halt exit_halt := rfl lemma boolList_push (b : Bool) (s : Word) : true::false::b::true::s=true::pair [b] s := rfl lemma runs_boolList {n : ℕ} (O : IndependenceOracle n) (x y s : Word) (bits : ℕ → Bool) : Runs boolListBlock O bits (regs (words (y.map (fun b => [b]))) x [] s) (regs (words ((x.reverse++y).map (fun b => [b]))) [] [] s) (5*x.length+1) 0 (5*x.length+1) := by intro q w induction x generalizing y w bits with | nil => simp [execution,machineStep,boolListBlock,state,lastLabel] | cons b xs ih => have hh : execution boolListBlock.code O (state (regs (words (y.map (fun b => [b]))) (b::xs) [] s) 0 q w) bits 5= state (regs (words ((b::y).map (fun b => [b]))) xs [] s) 0 q (w+5) := by cases b <;> simp [execution,machineStep,boolListBlock,state,words,pair,bitFrame,Nat.add_assoc] <;> rfl rw [List.length_cons,show 5*(xs.length+1)+1=5+(5*xs.length+1) by omega,execution_add,hh,ih] simp only [List.reverse_cons,List.append_assoc,List.singleton_append] congr 1; omega def boolListCode : Block 1 := seq (reverse 0 1) boolListBlock lemma computes_boolList {n : ℕ} (O : IndependenceOracle n) (x : Word) : Computes boolListCode O x (words (x.map (fun b => [b]))) (7*x.length+2) 0 (7*x.length+2) := by intro s bits have hr := runs_reverse (k:=1) 0 1 (by decide) O (regs [] [] [] s) x [] bits simp only [pairRegisters,update_regs_zero,update_regs_one,List.append_nil] at hr have hb := runs_boolList O x.reverse [] s (fun i => bits (2*x.length+1+i)) simp only [List.map_nil,words,List.reverse_reverse,List.append_nil,List.length_reverse] at hb have ht := runs_seq O bits hr hb convert ht using 1 <;> first | rfl | omega def consWordCode : Block 1 := seq (unpack 0 1) (fork (.pop 1 false false true) (push 0 false) (push 0 true)) lemma computes_consWord {n : ℕ} (O : IndependenceOracle n) (b : Bool) (x : Word) : Computes consWordCode O (pair [b] x) (b::x) 6 0 6 := by have h (b : Bool) : Computes (push 0 b) O x (b::x) 1 0 1 := by intro s bits simpa only [regs_zero,update_regs_zero] using runs_push O bits (regs x [] [] s) 0 b have ht := computes_select (push 0 false) (push 0 true) b (x:=x) (y:=b::x) (by cases b <;> exact h _) exact ht def consListCode : Block 1 := push 0 true lemma computes_consList {n : ℕ} (O : IndependenceOracle n) (x : Word) (xs : List Word) : Computes consListCode O (pair x (words xs)) (words (x::xs)) 1 0 1 := by intro s bits simpa only [regs_zero,update_regs_zero,consListCode,words] using runs_push O bits (regs (pair x (words xs)) [] [] s) 0 true def appendCode : Block 1 := seq (unpack 0 1) (move 1 2 0) lemma computes_append {n : ℕ} (O : IndependenceOracle n) (x y : Word) : Computes appendCode O (pair x y) (x++y) (7*x.length+3) 0 (7*x.length+3) := by intro s bits have hs := split_pair O x y [] s bits simp only [List.append_nil] at hs have hm := move_one_zero O x y s (fun i => bits (3*x.length+1+i)) simpa only [appendCode,Nat.zero_add,show 3*x.length+1+(4*x.length+2)=7*x.length+3 by omega] using runs_seq O bits hs hm def subBlock : Block 1 := ⟨16,subProgram 1 0 2,rfl⟩ def subTime (x y : Word) : ℕ := subCost false x y+2*(subDigits false x y).length+1 lemma runs_sub {n : ℕ} (O : IndependenceOracle n) (x y s : Word) (hxy : binaryValue y≤binaryValue x) (bits : ℕ → Bool) : Runs subBlock O bits (regs y x [] s) (regs [] (subDigits false x y) [] s) (subTime x y) 0 (subTime x y) := by dsimp only [Runs,subBlock] intro q w have h := (subtraction_block (k:=1) 1 0 2 (by decide) (by decide) (by decide) O (regs [] [] [] s) x y hxy q w bits).2.2 convert h using 1 <;> simp only [subTime,subConfig,state,tripleRegisters,pairRegisters,update_regs_zero, update_regs_one,update_regs_two,lastLabel,Nat.add_zero] rfl def subCode : Block 1 := seq (unpack 0 1) (seq subBlock (seq (move 1 2 0) normalCode)) lemma computes_sub {n : ℕ} (O : IndependenceOracle n) (x y : Word) (hxy : binaryValue y≤binaryValue x) : Computes subCode O (pair x y) (binaryValue x-binaryValue y).bits (3*x.length+1+subTime x y+4*(subDigits false x y).length+2+normalCost (subDigits false x y)) 0 (3*x.length+1+subTime x y+4*(subDigits false x y).length+2+normalCost (subDigits false x y)) := by have hv := (subtraction_block (k:=1) 1 0 2 (by decide) (by decide) (by decide) O (regs [] [] [] []) x y hxy 0 0 (fun _ => false)).1 intro s bits have hs := split_pair O x y [] s bits simp only [List.append_nil] at hs have hd := runs_sub O x y s hxy (fun i => bits (3*x.length+1+i)) have hm := move_one_zero O (subDigits false x y) [] s (fun i => bits (3*x.length+1+(subTime x y+i))) simp only [List.append_nil] at hm have hn := computes_normalCode O (subDigits false x y) s (fun i => bits (3*x.length+1+(subTime x y+(4*(subDigits false x y).length+2+i)))) rw [normalWord_eq_bits,hv] at hn have hh := runs_seq O bits hs (runs_seq O _ hd (runs_seq O _ hm hn)) convert hh using 1 <;> first | rfl | omega lemma bounded_sub {n : ℕ} (O : IndependenceOracle n) (x y : Word) (hxy : binaryValue y≤binaryValue x) : Bounded subCode O (pair x y) (binaryValue x-binaryValue y).bits (30*(x.length+y.length+1)) := by have h₁ := subDigits_length_cost false x y have h₂ := normalCost_le (subDigits false x y) refine ⟨_,0,_,?_,Nat.zero_le _,?_,computes_sub O x y hxy⟩ <;> dsimp only [subTime] <;> omega def rankPrep : Block 1 where size := 5 code := fun pc => match pc.val with | 0 => .pop 0 5 1 3 | 1 => .push 2 false 2 | 2 => .push 1 false 0 | 3 => .push 2 true 4 | 4 => .push 1 false 0 | _ => .halt exit_halt := rfl lemma runs_rankPrep {n : ℕ} (O : IndependenceOracle n) (x y z s : Word) (bits : ℕ → Bool) : Runs rankPrep O bits (regs x y z s) (regs [] (List.replicate x.length false++y) (x.reverse++z) s) (3*x.length+1) 0 (3*x.length+1) := by dsimp only [Runs] intro q w induction x generalizing y z w bits with | nil => simp [execution,machineStep,rankPrep,state,lastLabel] | cons b xs ih => have h : execution rankPrep.code O (state (regs (b::xs) y z s) 0 q w) bits 3= state (regs xs (false::y) (b::z) s) 0 q (w+3) := by cases b <;> simp [execution,machineStep,rankPrep,state,Nat.add_assoc] <;> rfl rw [List.length_cons,show 3*(xs.length+1)+1=3+(3*xs.length+1) by omega,execution_add,h,ih] simp only [List.reverse_cons,List.append_assoc,List.singleton_append,Nat.add_zero] congr 1 · simp [List.replicate_add,List.append_assoc] · omega lemma update_regs_three_empty (x y z s : Word) : Function.update (regs x y z s) 3 []=regs x y z s := by funext i; fin_cases i <;> simp [regs] lemma greedyRegisters_regs (x y z s : Word) : greedyRegisters (regs [] [] [] s) x y z []=regs x y z s := by funext i; fin_cases i <;> simp [greedyRegisters,regs] def readyRank (which : Bool) : Block 1 := ⟨32,rankProgram which,rfl⟩ def rankCode (which : Bool) : Block 1 := seq rankPrep (seq (move 2 3 0) (seq (readyRank which) normalCode)) def rankWord {n : ℕ} (O : IndependenceOracle n) (which : Bool) (x : Word) : ℕ := binaryValue (rankBits which O x.reverse) lemma popcountBits_length (xs ys : Word) : (popcountBits xs ys).length≤xs.length+ys.length := by induction xs generalizing ys with | nil => simp [popcountBits] | cons b xs ih => cases b with | false => simpa only [popcountBits,Bool.false_eq_true,ite_false,List.length_cons] using (ih ys).trans (by omega) | true => have h := ih (incrementBits ys) have hi := incrementBits_length ys simp only [popcountBits,ite_true,List.length_cons] omega lemma rankBits_length {n : ℕ} (O : IndependenceOracle n) (which : Bool) (x : Word) : (rankBits which O x).length≤x.length := by simpa only [rankBits,wordGreedy_length,List.length_nil,Nat.add_zero] using popcountBits_length (wordGreedy (wordOracle which O) x []) [] lemma computes_rank {n : ℕ} (O : IndependenceOracle n) (which : Bool) (x : Word) (hx : x.length=n) : Computes (rankCode which) O x (rankWord O which x).bits (7*n+3+rankTime which O x.reverse+normalCost (rankBits which O x.reverse)) (greedyCalls x.reverse) (7*n+3+rankWork which O x.reverse+normalCost (rankBits which O x.reverse)) := by intro s bits have hp := runs_rankPrep O x [] [] s bits simp only [hx,List.append_nil] at hp have hm := runs_move (k:=1) 2 3 0 (by decide) (by decide) (by decide) O (regs [] (List.replicate n false) [] s) x.reverse [] (fun i => bits (3*n+1+i)) simp only [tripleRegisters,pairRegisters,update_regs_zero,update_regs_two,update_regs_three_empty, List.append_nil,List.length_reverse,hx] at hm have hr : Runs (readyRank which) O (fun i => bits (3*n+1+(4*n+2+i))) (regs x.reverse (List.replicate n false) [] s) (regs (rankBits which O x.reverse) [] [] s) (rankTime which O x.reverse) (greedyCalls x.reverse) (rankWork which O x.reverse) := by intro q w convert rank_run which O (regs [] [] [] s) x.reverse (by simpa only [List.length_reverse] using hx) q w (fun i => bits (3*n+1+(4*n+2+i))) using 1 <;> (try simp only [readyRank,state,rankConfig,greedyRegisters_regs,lastLabel]) <;> rfl have hn := computes_normalCode O (rankBits which O x.reverse) s (fun i => bits (3*n+1+(4*n+2+(rankTime which O x.reverse+i)))) rw [normalWord_eq_bits] at hn have hh := runs_seq O bits hp (runs_seq O _ hm (runs_seq O _ hr hn)) convert hh using 1 <;> first | rfl | omega lemma bounded_rank {n : ℕ} (O : IndependenceOracle n) (which : Bool) (x : Word) (hx : x.length=n) : Bounded (rankCode which) O x (rankWord O which x).bits (100*(n+1)^2) := by have hr : x.reverse.length=n := by simpa only [List.length_reverse] using hx have ht := rankTime_bound which O x.reverse hr have hw := rankWork_bound which O x.reverse hr have hl := rankBits_length O which x.reverse have hn := normalCost_le (rankBits which O x.reverse) have hq := greedyCalls_bound x.reverse simp only [List.length_reverse,hx] at hl hq refine ⟨_,_,_,?_,?_,?_,computes_rank O which x hx⟩ <;> nlinarith lemma rankWord_correct {n : ℕ} (M₁ M₂ : Matroid (Fin n)) (O : IndependenceOracle n) (hO : ExactOracles M₁ M₂ O) (hE₁ : M₁.E=Set.univ) (hE₂ : M₂.E=Set.univ) (which : Bool) (x : Word) (hx : x.length=n) : rankWord O which x=((if which then M₂ else M₁).eRk (wordSet n x)).toNat := by simp only [rankWord,rankBits,popcount_value,binaryValue,Nat.zero_add] have hr := wordGreedy_rank (if which then M₂ else M₁) (by cases which <;> assumption) (wordOracle which O) (fun l _ => hO which (fun i => l[i.val]?.getD false)) x.reverse (by simpa only [List.length_reverse] using hx) simpa only [List.reverse_reverse] using hr open scoped Classical in lemma rankWord_eq_rankOracle {n : ℕ} (M₁ M₂ : Matroid (Fin n)) (O : IndependenceOracle n) (hO : ExactOracles M₁ M₂ O) (hE₁ : M₁.E=Set.univ) (hE₂ : M₂.E=Set.univ) (which : Bool) (x : Word) (hx : x.length=n) : rankWord O which x=rankOracle O which (wordSet n x).toFinset := by classical rw [rankWord_correct M₁ M₂ O hO hE₁ hE₂ which x hx, rankOracle_correct M₁ M₂ O hO hE₁ hE₂ which,Set.coe_toFinset] inductive DataType where | unit | bool | nat | word | prod : DataType → DataType → DataType | list : DataType → DataType @[reducible] def Value : DataType → Type | .unit => Unit | .bool => Bool | .nat => ℕ | .word => Word | .prod a b => Value a × Value b | .list a => List (Value a) def encode : {a : DataType} → Value a → Word | .unit,_ => [] | .bool,b => [b] | .nat,m => m.bits | .word,w => w | .prod _ _,(x,y) => pair (encode x) (encode y) | .list _,xs => words (xs.map encode) def width {a : DataType} (x : Value a) : ℕ := (encode x).length inductive Expression : DataType → DataType → Type where | ident {a} : Expression a a | constant {a b} : Value b → Expression a b | compose {a b c} : Expression a b → Expression b c → Expression a c | both {a b c} : Expression a b → Expression a c → Expression a (.prod b c) | fst {a b} : Expression (.prod a b) a | snd {a b} : Expression (.prod a b) b | branch {a b} : Expression a b → Expression a b → Expression (.prod .bool a) b | fold {a b} : Expression (.prod a b) b → Expression (.prod (.list a) b) b | cons {a} : Expression (.prod a (.list a)) (.list a) | consBit : Expression (.prod .bool .word) .word | append : Expression (.prod .word .word) .word | reverse : Expression .word .word | toList : Expression .word (.list .bool) | toBits : Expression .nat .word | toNat : Expression .word .nat | add : Expression (.prod .nat .nat) .nat | sub : Expression (.prod .nat .nat) .nat | rank : Bool → Expression .word .nat | mul : Expression (.prod .nat .nat) .nat | less : Expression (.prod .nat .nat) .bool | divRem : Expression (.prod .nat .nat) (.prod .nat .nat) | query : Bool → Expression .word .bool def compile : {a b : DataType} → Expression a b → Block 1 | _,_,.ident => skip 1 | _,_,.constant x => constCode (encode x) | _,_,.compose p q => seq (compile p) (compile q) | _,_,.both p q => fanout (compile p) (compile q) | _,_,.fst => first | _,_,.snd => second | _,_,.branch p q => selectCode (compile p) (compile q) | _,_,.fold p => foldCode (compile p) | _,_,.cons => consListCode | _,_,.consBit => consWordCode | _,_,.append => appendCode | _,_,.reverse => reverseCode | _,_,.toList => boolListCode | _,_,.toBits => skip 1 | _,_,.toNat => normalCode | _,_,.add => addCode | _,_,.sub => subCode | _,_,.rank b => rankCode b | _,_,.mul => mulCode | _,_,.less => cmpCode | _,_,.divRem => divCode | _,_,.query b => queryCode b def evalFold {a b : DataType} (step : Value (.prod a b) → Option (Value b × ℕ)) : List (Value a) → Value b → Option (Value b × ℕ) | [],z => some (z,0) | x::xs,z => do let (z',c) ← step (x,z) let (y,d) ← evalFold step xs z' pure (y,7+6*width x+6*width (a:=.list a) xs+c+d) def evaluate {n : ℕ} (O : IndependenceOracle n) : {a b : DataType} → Expression a b → Value a → Option (Value b × ℕ) | _,_,.ident,x => some (x,0) | _,_,.constant y,x => some (y,width x+width y+1) | _,_,.compose p q,x => do let (y,c) ← evaluate O p x let (z,d) ← evaluate O q y pure (z,c+d) | _,_,.both p q,x => do let (y,c) ← evaluate O p x let (z,d) ← evaluate O q x pure ((y,z),43*width x+39*width y+18*width z+50+c+d) | _,_,.fst,(x,y) => some (x,7*width x+width y+4) | _,_,.snd,(x,y) => some (y,4*width x+2) | _,_,.branch p q,(b,x) => do let (y,c) ← (if b then evaluate O q x else evaluate O p x) pure (y,5+c) | _,_,.fold p,(xs,z) => do let (y,c) ← evalFold (evaluate O p) xs z pure (y,3*width xs+2+c) | _,_,.cons,(x,xs) => some (x::xs,1) | _,_,.consBit,(b,xs) => some (b::xs,6) | _,_,.append,(x,y) => some (x++y,7*x.length+3) | _,_,.reverse,x => some (x.reverse,6*x.length+3) | _,_,.toList,x => some (x,7*x.length+2) | _,_,.toBits,x => some (x.bits,0) | _,_,.toNat,x => some (binaryValue x,5*x.length+4) | _,_,.add,(x,y) => some (x+y,20*(x.bits.length+y.bits.length+1)) | _,_,.sub,(x,y) => if y≤x then some (x-y,30*(x.bits.length+y.bits.length+1)) else none | _,_,.rank b,x => if x.length=n then some (rankWord O b x,100*(n+1)^2) else none | _,_,.mul,(x,y) => some (x*y,60*(x.bits.length+y.bits.length+1)^2) | _,_,.less,(x,y) => some (decide (x if x=0 then none else some ((y%x,y/x),300*(x.bits.length+y.bits.length+1)^2) | _,_,.query b,x => if x.length=n then some (O b (fun i => x[i.val]?.getD false),3*n+3) else none lemma bounded_fanout {n : ℕ} {O : IndependenceOracle n} {p q : Block 1} {x y z : Word} {B C : ℕ} (h : Bounded p O x y B) (g : Bounded q O x z C) : Bounded (fanout p q) O x (pair y z) (43*x.length+39*y.length+18*z.length+50+B+C) := by obtain ⟨t,a,w,ht,ha,hw,hp⟩ := h obtain ⟨u,b,v,hu,hb,hv,hq⟩ := g refine ⟨_,_,_,?_,?_,?_,computes_fanout hp hq⟩ <;> omega lemma bounded_select {n : ℕ} {O : IndependenceOracle n} (p q : Block 1) (b : Bool) {x y : Word} {B : ℕ} (h : Bounded (if b then q else p) O x y B) : Bounded (selectCode p q) O (pair [b] x) y (5+B) := by obtain ⟨t,a,w,ht,ha,hw,hp⟩ := h refine ⟨_,_,_,?_,?_,?_,computes_select p q b hp⟩ <;> omega lemma computes_bounded {n : ℕ} {O : IndependenceOracle n} {p : Block 1} {x y : Word} {c : ℕ} (h : Computes p O x y c 0 c) : Bounded p O x y c := ⟨c,0,c,le_rfl,Nat.zero_le _,le_rfl,h⟩ lemma evalFold_loop {n : ℕ} {O : IndependenceOracle n} {a b : DataType} (p : Block 1) (f : Value (.prod a b) → Option (Value b × ℕ)) (hf : ∀ x y c, f x=some (y,c) → Bounded p O (encode x) (encode y) c) (xs : List (Value a)) (z y : Value b) (c : ℕ) (h : evalFold f xs z=some (y,c)) : ∃ t q w, t≤1+c ∧ q≤c ∧ w≤1+c ∧ ∀ s bits, Runs (repeatBlock (listBody p) 1) O bits (regs (encode z) (encode (a:=.list a) xs) [] s) (regs (encode y) [] [] s) t q w := by induction xs generalizing z y c with | nil => simp only [evalFold,Option.some.injEq,Prod.mk.injEq] at h rcases h with ⟨rfl,rfl⟩ refine ⟨1,0,1,by omega,by omega,by omega,?_⟩ intro s bits dsimp only [Runs, repeatBlock] intro q w simpa only [repeatBlock,state,loopConfig,encode,List.map_nil,words,Nat.add_zero,update_regs_one] using repeatProgram_empty (listBody p).code 1 O (regs (encode z) [] [] s) q w bits | cons x xs ih => cases h₁ : f (x,z) with | none => simp [evalFold,h₁] at h | some r => rcases r with ⟨z',c₁⟩ cases h₂ : evalFold f xs z' with | none => simp [evalFold,h₁,h₂] at h | some r => rcases r with ⟨y',c₂⟩ simp [evalFold,h₁,h₂] at h rcases h with ⟨rfl,rfl⟩ obtain ⟨t₁,q₁,w₁,ht₁,hq₁,hw₁,hp⟩ := hf _ _ _ h₁ obtain ⟨t₂,q₂,w₂,ht₂,hq₂,hw₂,hr⟩ := ih z' y' c₂ h₂ refine ⟨7+6*width x+6*width (a:=.list a) xs+t₁+t₂,q₁+q₂, 7+6*width x+6*width (a:=.list a) xs+w₁+w₂,by omega,by omega,by omega,?_⟩ intro s bits have hb := list_body hp (encode (a:=.list a) xs) s (fun i => bits (1+i)) have hh := runs_repeat_cons (R:=regs (encode z) [] [] s) (b:=true) (by simpa only [update_regs_one] using hb) (hr s (fun i => bits (1+(6*(encode x).length+6*(encode (a:=.list a) xs).length+6+t₁)+i))) simp only [update_regs_one] at hh convert hh using 1 <;> first | rfl | (dsimp only [width]; omega) lemma evalFold_bounded {n : ℕ} {O : IndependenceOracle n} {a b : DataType} (p : Block 1) (f : Value (.prod a b) → Option (Value b × ℕ)) (hf : ∀ x y c, f x=some (y,c) → Bounded p O (encode x) (encode y) c) (xs : List (Value a)) (z y : Value b) (c : ℕ) (h : evalFold f xs z=some (y,c)) : Bounded (foldCode p) O (encode (a:=.prod (.list a) b) (xs,z)) (encode y) (3*width (a:=.list a) xs+2+c) := by obtain ⟨t,q,w,ht,hq,hw,hl⟩ := evalFold_loop p f hf xs z y c h refine ⟨3*width (a:=.list a) xs+1+t,q,3*width (a:=.list a) xs+1+w,by omega,by omega,by omega,?_⟩ intro s bits have hs := split_pair O (encode (a:=.list a) xs) (encode z) [] s bits simp only [List.append_nil] at hs simpa only [Nat.zero_add, foldCode, encode, width] using runs_seq O bits hs (hl s (fun i => bits (3*width (a:=.list a) xs+1+i))) theorem compile_correct {n : ℕ} (O : IndependenceOracle n) {a b : DataType} (e : Expression a b) : ∀ x y c, evaluate O e x=some (y,c) → Bounded (compile e) O (encode x) (encode y) c := by induction e with | ident => intro x y c h simp only [evaluate,Option.some.injEq,Prod.mk.injEq] at h rcases h with ⟨rfl,rfl⟩ exact computes_bounded (computes_skip O _) | constant v => intro x y c h simp only [evaluate,Option.some.injEq,Prod.mk.injEq] at h rcases h with ⟨rfl,rfl⟩ exact computes_bounded (computes_const O _ _) | compose p q ihp ihq => intro x y c h cases hp : evaluate O p x with | none => simp [evaluate,hp] at h | some r => rcases r with ⟨z,d⟩ cases hq : evaluate O q z with | none => simp [evaluate,hp,hq] at h | some r => rcases r with ⟨v,f⟩ simp [evaluate,hp,hq] at h rcases h with ⟨rfl,rfl⟩ exact bounded_seq (ihp _ _ _ hp) (ihq _ _ _ hq) | both p q ihp ihq => intro x y c h cases hp : evaluate O p x with | none => simp [evaluate,hp] at h | some r => rcases r with ⟨z,d⟩ cases hq : evaluate O q x with | none => simp [evaluate,hp,hq] at h | some r => rcases r with ⟨v,f⟩ simp [evaluate,hp,hq] at h rcases h with ⟨rfl,rfl⟩ exact bounded_fanout (ihp _ _ _ hp) (ihq _ _ _ hq) | fst => intro ⟨x,z⟩ y c h simp only [evaluate,Option.some.injEq,Prod.mk.injEq] at h rcases h with ⟨rfl,rfl⟩ exact computes_bounded (computes_first O _ _) | snd => intro ⟨x,z⟩ y c h simp only [evaluate,Option.some.injEq,Prod.mk.injEq] at h rcases h with ⟨rfl,rfl⟩ exact computes_bounded (computes_second O _ _) | branch p q ihp ihq => intro ⟨b,x⟩ y c h have he : (if b then evaluate O q x else evaluate O p x)=evaluate O (if b then q else p) x := by cases b <;> rfl cases hp : evaluate O (if b then q else p) x with | none => simp [evaluate,he,hp] at h | some r => rcases r with ⟨z,d⟩ simp [evaluate,he,hp] at h rcases h with ⟨rfl,rfl⟩ apply bounded_select cases b with | false => exact ihp _ _ _ hp | true => exact ihq _ _ _ hp | fold p ih => intro ⟨xs,z⟩ y c h cases hp : evalFold (evaluate O p) xs z with | none => simp [evaluate,hp] at h | some r => rcases r with ⟨v,d⟩ simp [evaluate,hp] at h rcases h with ⟨rfl,rfl⟩ exact evalFold_bounded (compile p) (evaluate O p) ih xs z v d hp | cons => intro ⟨x,xs⟩ y c h simp only [evaluate,Option.some.injEq,Prod.mk.injEq] at h rcases h with ⟨rfl,rfl⟩ exact computes_bounded (computes_consList O _ _) | consBit => intro ⟨b,x⟩ y c h simp only [evaluate,Option.some.injEq,Prod.mk.injEq] at h rcases h with ⟨rfl,rfl⟩ exact computes_bounded (computes_consWord O _ _) | append => intro ⟨x,z⟩ y c h simp only [evaluate,Option.some.injEq,Prod.mk.injEq] at h rcases h with ⟨rfl,rfl⟩ exact computes_bounded (computes_append O _ _) | reverse => intro x y c h simp only [evaluate,Option.some.injEq,Prod.mk.injEq] at h rcases h with ⟨rfl,rfl⟩ exact computes_bounded (computes_reverse O _) | toList => intro x y c h simp only [evaluate,Option.some.injEq,Prod.mk.injEq] at h rcases h with ⟨rfl,rfl⟩ exact computes_bounded (computes_boolList O _) | toBits => intro x y c h simp only [evaluate,Option.some.injEq,Prod.mk.injEq] at h rcases h with ⟨rfl,rfl⟩ exact computes_bounded (computes_skip O _) | toNat => intro x y c h simp only [evaluate,Option.some.injEq,Prod.mk.injEq] at h rcases h with ⟨rfl,rfl⟩ have hh := computes_bounded (computes_normalCode O x) rw [normalWord_eq_bits] at hh exact bounded_mono hh (normalCost_le x) | add => intro ⟨x,z⟩ y c h simp only [evaluate,Option.some.injEq,Prod.mk.injEq] at h rcases h with ⟨rfl,rfl⟩ simpa only [compile, encode, binaryValue_bits] using bounded_add O x.bits z.bits | sub => intro ⟨x,z⟩ y c h simp only [evaluate] at h by_cases hx : z≤x · simp only [ite_eq_left hx,Option.some.injEq,Prod.mk.injEq] at h rcases h with ⟨rfl,rfl⟩ simpa only [compile,encode,binaryValue_bits] using bounded_sub O x.bits z.bits (by simpa only [binaryValue_bits] using hx) · simp [hx] at h | rank b => intro x y c h simp only [evaluate] at h by_cases hx : x.length=n · simp only [ite_eq_left hx,Option.some.injEq,Prod.mk.injEq] at h rcases h with ⟨rfl,rfl⟩ exact bounded_rank O b x hx · simp [hx] at h | mul => intro ⟨x,z⟩ y c h simp only [evaluate,Option.some.injEq,Prod.mk.injEq] at h rcases h with ⟨rfl,rfl⟩ simpa only [compile, encode, binaryValue_bits] using bounded_mul O x.bits z.bits | less => intro ⟨x,z⟩ y c h simp only [evaluate,Option.some.injEq,Prod.mk.injEq] at h rcases h with ⟨rfl,rfl⟩ simpa only [compile, encode, binaryValue_bits] using bounded_cmp O x.bits z.bits | divRem => intro ⟨x,z⟩ y c h simp only [evaluate] at h by_cases hx : x=0 · simp [hx] at h · simp only [ite_eq_right hx] at h simp only [Option.some.injEq,Prod.mk.injEq] at h rcases h with ⟨rfl,rfl⟩ have hh := bounded_div O x.bits z.bits rw [normalizedResult_pos _ _ (by simpa only [binaryValue_bits] using Nat.pos_of_ne_zero hx)] at hh simpa only [compile, encode, binaryValue_bits] using hh | query b => intro x y c h simp only [evaluate] at h by_cases hx : x.length=n · simp only [ite_eq_left hx] at h simp only [Option.some.injEq,Prod.mk.injEq] at h rcases h with ⟨rfl,rfl⟩ exact ⟨n+3,1,3*n+3,by omega,by omega,le_rfl,computes_query O b x hx⟩ · simp [hx] at h def foldValue {A B : Type*} (step : A × B → Option B) : List A → B → Option B | [],z => some z | x::xs,z => (step (x,z)).bind (foldValue step xs) def run {n : ℕ} (O : IndependenceOracle n) : {a b : DataType} → Expression a b → Value a → Option (Value b) | _,_,.ident,x => some x | _,_,.constant y,_ => some y | _,_,.compose p q,x => (run O p x).bind (run O q) | _,_,.both p q,x => do let y ← run O p x; let z ← run O q x; pure (y,z) | _,_,.fst,(x,_) => some x | _,_,.snd,(_,y) => some y | _,_,.branch p q,(b,x) => if b then run O q x else run O p x | _,_,.fold p,(xs,z) => foldValue (run O p) xs z | _,_,.cons,(x,xs) => some (x::xs) | _,_,.consBit,(b,xs) => some (b::xs) | _,_,.append,(x,y) => some (x++y) | _,_,.reverse,x => some x.reverse | _,_,.toList,x => some x | _,_,.toBits,x => some x.bits | _,_,.toNat,x => some (binaryValue x) | _,_,.add,(x,y) => some (x+y) | _,_,.sub,(x,y) => if y≤x then some (x-y) else none | _,_,.mul,(x,y) => some (x*y) | _,_,.less,(x,y) => some (decide (x if x=0 then none else some (y%x,y/x) | _,_,.query b,x => if x.length=n then some (O b (fun i => x[i.val]?.getD false)) else none | _,_,.rank b,x => if x.length=n then some (rankWord O b x) else none lemma evalFold_forget {a b : DataType} (f : Value (.prod a b) → Option (Value b × ℕ)) (g : Value (.prod a b) → Option (Value b)) (hfg : ∀ x,(f x).map Prod.fst=g x) (xs : List (Value a)) (z : Value b) : (evalFold f xs z).map Prod.fst=foldValue g xs z := by induction xs generalizing z with | nil => rfl | cons x xs ih => rw [evalFold,foldValue,←hfg] cases hf : f (x,z) with | none => rfl | some r => rcases r with ⟨z',c⟩ simp only [Option.map_some,Option.bind_some] rw [←ih] cases hh : evalFold f xs z' <;> simp [hh] lemma evaluate_forget {n : ℕ} (O : IndependenceOracle n) {a b : DataType} (e : Expression a b) (x : Value a) : (evaluate O e x).map Prod.fst=run O e x := by induction e with | compose p q ihp ihq => simp only [evaluate,run,←ihp] cases hp : evaluate O p x with | none => rfl | some r => rcases r with ⟨y,c⟩ simp only [Option.map_some,Option.bind_some] rw [←ihq] cases hh : evaluate O q y <;> simp [hh] | both p q ihp ihq => simp only [evaluate,run,←ihp,←ihq] cases evaluate O p x <;> cases evaluate O q x <;> rfl | branch p q ihp ihq => rcases x with ⟨b,x⟩ cases b <;> simp only [evaluate,run,Bool.false_eq_true,ite_false,ite_true,←ihp,←ihq] <;> first | (cases evaluate O p x <;> rfl) | (cases evaluate O q x <;> rfl) | fold p ih => rcases x with ⟨xs,z⟩ simp only [evaluate,run,←evalFold_forget (evaluate O p) (run O p) ih xs z] cases evalFold (evaluate O p) xs z <;> rfl | divRem => rcases x with ⟨x,y⟩; simp only [evaluate,run]; split_ifs <;> rfl | sub => rcases x with ⟨x,y⟩; simp only [evaluate,run]; split_ifs <;> rfl | query b => simp only [evaluate,run]; split_ifs <;> rfl | rank b => simp only [evaluate,run]; split_ifs <;> rfl | _ => rfl lemma compile_run {n : ℕ} (O : IndependenceOracle n) {a b : DataType} (e : Expression a b) (x : Value a) (y : Value b) (h : run O e x=some y) : ∃ B, Bounded (compile e) O (encode x) (encode y) B := by rw [←evaluate_forget] at h cases he : evaluate O e x with | none => simp [he] at h | some r => rcases r with ⟨y',c⟩ simp only [he,Option.map_some,Option.some.injEq] at h subst y' exact ⟨c,compile_correct O e x y c he⟩ namespace Expression infixr:80 " >>> " => compose def onLeft {a b c} (p : Expression a b) : Expression (.prod a c) (.prod b c) := both (fst >>> p) snd def onRight {a b c} (p : Expression a b) : Expression (.prod c a) (.prod c b) := both fst (snd >>> p) def swap {a b} : Expression (.prod a b) (.prod b a) := both snd fst def letIn {a b c} (p : Expression a b) (q : Expression (.prod a b) c) : Expression a c := both ident p >>> q def applyIf {a b} (test : Expression a .bool) (no yes : Expression a b) : Expression a b := both test ident >>> branch no yes def boolNot : Expression .bool .bool := both ident ident >>> branch (constant true) (constant false) def boolAnd : Expression (.prod .bool .bool) .bool := branch (constant false) ident def natEqZero : Expression .nat .bool := both ident (constant 1) >>> less def natSub : Expression (.prod .nat .nat) .nat := applyIf less sub (constant 0) def natDivRem : Expression (.prod .nat .nat) (.prod .nat .nat) := applyIf (fst >>> natEqZero) divRem (both snd (constant 0)) def natDiv : Expression (.prod .nat .nat) .nat := natDivRem >>> snd def natMod : Expression (.prod .nat .nat) .nat := natDivRem >>> fst def listReverse {a} : Expression (.list a) (.list a) := both ident (constant []) >>> fold cons def mapStep {a b c} (p : Expression (.prod a c) b) : Expression (.prod a (.prod (.list b) c)) (.prod (.list b) c) := both (both (both fst (snd >>> snd) >>> p) (snd >>> fst) >>> cons) (snd >>> snd) def mapWith {a b c} (p : Expression (.prod a c) b) : Expression (.prod (.list a) c) (.list b) := both fst (both (constant []) snd) >>> fold (mapStep p) >>> fst >>> listReverse def listLength {a} : Expression (.list a) .nat := both ident (constant 0) >>> fold (both snd (constant 1) >>> add) def wordLength : Expression .word .nat := toList >>> listLength def wordRepeatStep : Expression (.prod .bool .word) .word := letIn (snd >>> both ident ident >>> append) (both fst snd >>> both (fst >>> fst) snd >>> branch ident (both (constant false) ident >>> consBit)) def unary : Expression .nat .word := both (toBits >>> reverse >>> toList) (constant []) >>> fold wordRepeatStep end Expression lemma foldValue_eq_foldl {a b : DataType} (f : Value (.prod a b) → Option (Value b)) (g : Value b → Value a → Value b) (hf : ∀ x z, f (x,z)=some (g z x)) (xs : List (Value a)) (z : Value b) : foldValue f xs z=some (xs.foldl g z) := by induction xs generalizing z with | nil => rfl | cons x xs ih => simp [foldValue,hf,ih] namespace Expression variable {n : ℕ} (O : IndependenceOracle n) @[simp] lemma run_boolNot (b : Bool) : run O boolNot b=some (!b) := by cases b <;> rfl @[simp] lemma run_boolAnd (b c : Bool) : run O boolAnd (b,c)=some (b && c) := by cases b <;> rfl @[simp] lemma run_natEqZero (m : ℕ) : run O natEqZero m=some (decide (m=0)) := by simp [natEqZero,run] @[simp] lemma run_natSub (x y : ℕ) : run O natSub (x,y)=some (x-y) := by simp only [natSub,applyIf,run] by_cases h : x simp [h] @[simp] lemma run_natDiv (x y : ℕ) : run O natDiv (x,y)=some (y/x) := by change ((run O natDivRem (x,y)).bind fun p => some p.2)=some (y/x) rw [run_natDivRem]; rfl @[simp] lemma run_natMod (x y : ℕ) : run O natMod (x,y)=some (y%x) := by change ((run O natDivRem (x,y)).bind fun p => some p.1)=some (y%x) rw [run_natDivRem]; rfl lemma run_listReverse {a : DataType} (xs : List (Value a)) : run O listReverse xs=some xs.reverse := by simp only [listReverse,run] have h := foldValue_eq_foldl (fun p : Value (.prod a (.list a)) => some (p.1::p.2)) (fun zs x => x::zs) (fun _ _ => rfl) xs [] simpa using h lemma run_mapStep {a b c : DataType} (p : Expression (.prod a c) b) (f : Value a → Value c → Value b) (hp : ∀ x z, run O p (x,z)=some (f x z)) (x : Value a) (xs : List (Value b)) (z : Value c) : run O (mapStep p) (x,(xs,z))=some (f x z::xs,z) := by simp [mapStep,run,hp] lemma run_mapWith {a b c : DataType} (p : Expression (.prod a c) b) (f : Value a → Value c → Value b) (hp : ∀ x z, run O p (x,z)=some (f x z)) (xs : List (Value a)) (z : Value c) : run O (mapWith p) (xs,z)=some (xs.map (fun x => f x z)) := by have hf : ∀ (ys : List (Value a)) (acc : List (Value b)), foldValue (run O (mapStep p)) ys (acc,z)=some ((ys.map (fun x => f x z)).reverse++acc,z) := by intro ys induction ys with | nil => intro acc; rfl | cons x ys ih => intro acc; simp [foldValue,run_mapStep O p f hp,ih,List.append_assoc] simp [mapWith,run,hf,run_listReverse] lemma run_listLength {a : DataType} (xs : List (Value a)) : run O listLength xs=some xs.length := by have hf : ∀ (ys : List (Value a)) (z : ℕ), foldValue (fun p : Value (.prod a .nat) => some (p.2+1)) ys z=some (z+ys.length) := by intro ys induction ys with | nil => intro z; simp [foldValue] | cons x ys ih => intro z; simpa [foldValue,ih] using congrArg some (by omega : z+1+ys.length=z+(ys.length+1)) simp [listLength,run,hf] lemma run_wordLength (xs : Word) : run O wordLength xs=some xs.length := by simp [wordLength,run,run_listLength] lemma run_wordRepeatStep (b : Bool) (w : Word) : run O wordRepeatStep (b,w)=some (if b then false::(w++w) else w++w) := by cases b <;> rfl lemma unary_value (xs : List Bool) (w : Word) : ∃ out, foldValue (run O wordRepeatStep) xs.reverse w=some out ∧ out.length=2^xs.length*w.length+binaryValue xs := by induction xs generalizing w with | nil => exact ⟨w,rfl,by simp [binaryValue]⟩ | cons b xs ih => obtain ⟨u,hu,hl⟩ := ih w have happ : ∀ (ys zs : List Bool) v, foldValue (run O wordRepeatStep) (ys++zs) v= (foldValue (run O wordRepeatStep) ys v).bind (foldValue (run O wordRepeatStep) zs) := by intro ys induction ys with | nil => intros; rfl | cons y ys ih => intros; simp [foldValue,ih,Option.bind_assoc] refine ⟨(if b then false::(u++u) else u++u),?_,?_⟩ · rw [List.reverse_cons,happ,hu] simp only [Option.bind_some,foldValue] rw [run_wordRepeatStep]; rfl · cases b <;> simp [List.length_append,hl,binaryValue,Nat.pow_succ] <;> ring lemma run_unary (m : ℕ) : ∃ w,run O unary m=some w ∧ w.length=m := by obtain ⟨w,hw,hlen⟩ := unary_value O m.bits [] refine ⟨w,?_,?_⟩ · simpa [unary,run] using hw · simpa [binaryValue_bits] using hlen end Expression @[simp] lemma width_pair {a b : DataType} (x : Value a) (y : Value b) : width (a:=.prod a b) (x,y)=2*width x+1+width y := by simp [width,encode] @[simp] lemma width_nil {a : DataType} : width (a:=.list a) []=0 := rfl @[simp] lemma width_cons {a : DataType} (x : Value a) (xs : List (Value a)) : width (a:=.list a) (x::xs)=2*width x+2+width (a:=.list a) xs := by simp [width,encode,words]; omega lemma list_length_le_width {a : DataType} (xs : List (Value a)) : xs.length≤width (a:=.list a) xs := by induction xs with | nil => rfl | cons x xs ih => simp only [List.length_cons,width_cons]; omega def FoldSafe {A B : Type*} (ok : A×B → Prop) (f : A×B → Option B) : List A → B → Prop | [],_ => True | x::xs,z => ok (x,z) ∧ ∀ y,f (x,z)=some y → FoldSafe ok f xs y def Safe {n : ℕ} (O : IndependenceOracle n) (S : ℕ) : {a b : DataType} → Expression a b → Value a → Prop | _,_,e,x => width x≤S ∧ (∀ y,run O e x=some y → width y≤S) ∧ match e,x with | .compose p q,x => Safe O S p x ∧ ∀ y,run O p x=some y → Safe O S q y | .both p q,x => Safe O S p x ∧ Safe O S q x | .branch p q,(b,x) => if b then Safe O S q x else Safe O S p x | .fold p,(xs,z) => FoldSafe (Safe O S p) (run O p) xs z | _,_ => True lemma safe_input {n S : ℕ} {O : IndependenceOracle n} {a b : DataType} {p : Expression a b} {x : Value a} (h : Safe O S p x) : width x≤S := by cases p <;> exact h.1 lemma safe_output {n S : ℕ} {O : IndependenceOracle n} {a b : DataType} {p : Expression a b} {x : Value a} (h : Safe O S p x) {y : Value b} (hr : run O p x=some y) : width y≤S := by cases p <;> exact h.2.1 y hr def chargeBound : {a b : DataType} → Expression a b → ℕ → ℕ | _,_,.compose p q,T => 10000*(T+1)^2+chargeBound p T+chargeBound q T | _,_,.both p q,T => 10000*(T+1)^2+chargeBound p T+chargeBound q T | _,_,.branch p q,T => 10000*(T+1)^2+chargeBound p T+chargeBound q T | _,_,.fold p,T => 10000*(T+1)^2+(T+1)*(10000*(T+1)^2+chargeBound p T) | _,_,_,T => 10000*(T+1)^2 lemma evalFold_charge {n : ℕ} (O : IndependenceOracle n) {a b : DataType} (p : Expression (.prod a b) b) (S E : ℕ) (hp : ∀ x y c,Safe O S p x → evaluate O p x=some (y,c) → c≤E) (xs : List (Value a)) (z y : Value b) (c : ℕ) (hs : FoldSafe (Safe O S p) (run O p) xs z) (hw : width (a:=.list a) xs≤S) (he : evalFold (evaluate O p) xs z=some (y,c)) : c≤xs.length*(7+12*S+E) := by induction xs generalizing z y c with | nil => simp [evalFold] at he; rcases he with ⟨rfl,rfl⟩; simp | cons x xs ih => rw [evalFold] at he cases hh : evaluate O p (x,z) with | none => simp [hh] at he | some u => rcases u with ⟨z',d⟩ have hrun : run O p (x,z)=some z' := by rw [←evaluate_forget,hh]; rfl have hd := hp (x,z) z' d hs.1 hh have hw' : width (a:=.list a) xs≤S := by rw [width_cons] at hw; omega have hx : width x≤S := by rw [width_cons] at hw; omega cases ht : evalFold (evaluate O p) xs z' with | none => simp [hh,ht] at he | some u => rcases u with ⟨y',e⟩ simp [hh,ht] at he rcases he with ⟨rfl,rfl⟩ have hh := ih z' y' e (hs.2 z' hrun) hw' ht simp only [List.length_cons,Nat.add_mul,Nat.one_mul] omega lemma charge_primitive (T : ℕ) : 300*(2*T+1)^2+100*T+100≤10000*(T+1)^2 := by nlinarith lemma evaluate_charge {n : ℕ} (O : IndependenceOracle n) {a b : DataType} (p : Expression a b) (S : ℕ) (x : Value a) (y : Value b) (c : ℕ) (hs : Safe O S p x) (he : evaluate O p x=some (y,c)) : c≤chargeBound p (S+n) := by induction p generalizing S c with | compose p q ihp ihq => rcases hs with ⟨hx,hy,hp,hq⟩ simp only [evaluate] at he cases hpv : evaluate O p x with | none => simp [hpv] at he | some u => rcases u with ⟨z,d⟩ have hr : run O p x=some z := by rw [←evaluate_forget,hpv]; rfl have hd := ihp S x z d hp hpv cases hqv : evaluate O q z with | none => simp [hpv,hqv] at he | some u => rcases u with ⟨y',e⟩ simp [hpv,hqv] at he rcases he with ⟨rfl,rfl⟩ have hh := ihq S z y' e (hq z hr) hqv simp only [chargeBound]; omega | both p q ihp ihq => rcases hs with ⟨hx,hy,hp,hq⟩ simp only [evaluate] at he cases hpv : evaluate O p x with | none => simp [hpv] at he | some u => rcases u with ⟨z,d⟩ have hr : run O p x=some z := by rw [←evaluate_forget,hpv]; rfl have hz := safe_output hp hr have hd := ihp S x z d hp hpv cases hqv : evaluate O q x with | none => simp [hpv,hqv] at he | some u => rcases u with ⟨z',e⟩ have hr' : run O q x=some z' := by rw [←evaluate_forget,hqv]; rfl have hz' := safe_output hq hr' simp [hpv,hqv] at he rcases he with ⟨rfl,rfl⟩ have hh := ihq S x z' e hq hqv have hb := charge_primitive (S+n) simp only [chargeBound]; nlinarith | branch p q ihp ihq => rcases x with ⟨b,x⟩ rcases hs with ⟨hx,hy,hh⟩ cases b <;> simp only [Bool.false_eq_true,ite_false,ite_true] at hh <;> simp only [evaluate,Bool.false_eq_true,ite_false,ite_true] at he · cases hv : evaluate O p x with | none => simp [hv] at he | some u => rcases u with ⟨y',d⟩ simp [hv] at he rcases he with ⟨rfl,rfl⟩ have hd := ihp S x y' d hh hv have hb := charge_primitive (S+n) simp only [chargeBound]; omega · cases hv : evaluate O q x with | none => simp [hv] at he | some u => rcases u with ⟨y',d⟩ simp [hv] at he rcases he with ⟨rfl,rfl⟩ have hd := ihq S x y' d hh hv have hb := charge_primitive (S+n) simp only [chargeBound]; omega | fold p ih => rcases x with ⟨xs,z⟩ rcases hs with ⟨hx,hy,hh⟩ have hw : width (a:=.list _) xs≤S := by rw [width_pair] at hx; omega have hlen := list_length_le_width xs simp only [evaluate] at he cases hv : evalFold (evaluate O p) xs z with | none => simp [hv] at he | some u => rcases u with ⟨y',d⟩ simp [hv] at he rcases he with ⟨rfl,rfl⟩ have hd := evalFold_charge O p S (chargeBound p (S+n)) (fun x y c => ih S x y c) xs z y' d hh hw hv have hb := charge_primitive (S+n) have hmul : xs.length*(7+12*S+chargeBound p (S+n))≤(S+n+1)*(10000*(S+n+1)^2+chargeBound p (S+n)) := Nat.mul_le_mul (by omega) (by omega) simp only [chargeBound]; omega | ident => simp only [evaluate,Option.some.injEq,Prod.mk.injEq] at he; rcases he with ⟨rfl,rfl⟩; exact Nat.zero_le _ | constant z => have hx := safe_input hs have hz := safe_output hs (y:=z) rfl simp only [evaluate,Option.some.injEq,Prod.mk.injEq] at he rcases he with ⟨rfl,rfl⟩ have hb := charge_primitive (S+n) simp only [chargeBound]; omega | fst => rcases x with ⟨u,v⟩ have hx := safe_input hs rw [width_pair] at hx simp only [evaluate,Option.some.injEq,Prod.mk.injEq] at he rcases he with ⟨rfl,rfl⟩ have hb := charge_primitive (S+n) simp only [chargeBound]; omega | snd => rcases x with ⟨u,v⟩ have hx := safe_input hs rw [width_pair] at hx simp only [evaluate,Option.some.injEq,Prod.mk.injEq] at he rcases he with ⟨rfl,rfl⟩ have hb := charge_primitive (S+n) simp only [chargeBound]; omega | cons | consBit | append | add | sub | mul | less | divRem => rcases x with ⟨x,y⟩ have hx := safe_input hs have hb := charge_primitive (S+n) try simp only [width_pair] at hx simp only [evaluate] at he try split_ifs at he all_goals simp only [Option.some.injEq,Prod.mk.injEq] at he try contradiction rcases he with ⟨rfl,rfl⟩ simp only [chargeBound,width,encode,pair_length] at hx ⊢ nlinarith | reverse | toList | toBits | toNat | rank | query => have hx := safe_input hs have hb := charge_primitive (S+n) simp only [evaluate] at he try split_ifs at he all_goals simp only [Option.some.injEq,Prod.mk.injEq] at he try contradiction rcases he with ⟨rfl,rfl⟩ simp only [chargeBound,width,encode] at hx ⊢ nlinarith def chargeDegree : {a b : DataType} → Expression a b → ℕ | _,_,.compose p q => chargeDegree p+chargeDegree q+3 | _,_,.both p q => chargeDegree p+chargeDegree q+3 | _,_,.branch p q => chargeDegree p+chargeDegree q+3 | _,_,.fold p => chargeDegree p+3 | _,_,_ => 2 def chargeCoefficient : {a b : DataType} → Expression a b → ℕ | _,_,.compose p q => 10000+chargeCoefficient p+chargeCoefficient q | _,_,.both p q => 10000+chargeCoefficient p+chargeCoefficient q | _,_,.branch p q => 10000+chargeCoefficient p+chargeCoefficient q | _,_,.fold p => 20000+chargeCoefficient p | _,_,_ => 10000 lemma monomial_add_bound (T C D e f x y : ℕ) (hx : x≤C*(T+1)^e) (hy : y≤D*(T+1)^f) : 10000*(T+1)^2+x+y≤(10000+C+D)*(T+1)^(e+f+3) := by have hbase : 1≤T+1 := by omega have hp : (T+1)^2≤(T+1)^(e+f+3) := Nat.pow_le_pow_right hbase (by omega) have he : (T+1)^e≤(T+1)^(e+f+3) := Nat.pow_le_pow_right hbase (by omega) have hf : (T+1)^f≤(T+1)^(e+f+3) := Nat.pow_le_pow_right hbase (by omega) have hx' := hx.trans (Nat.mul_le_mul_left C he) have hy' := hy.trans (Nat.mul_le_mul_left D hf) calc _ ≤ 10000*(T+1)^(e+f+3)+C*(T+1)^(e+f+3)+D*(T+1)^(e+f+3) := by omega _ = _ := by ring lemma monomial_fold_bound (T C e x : ℕ) (hx : x≤C*(T+1)^e) : 10000*(T+1)^2+(T+1)*(10000*(T+1)^2+x)≤(20000+C)*(T+1)^(e+3) := by have hbase : 1≤T+1 := by omega have hp : (T+1)^2≤(T+1)^(e+3) := Nat.pow_le_pow_right hbase (by omega) have hq : (T+1)^3≤(T+1)^(e+3) := Nat.pow_le_pow_right hbase (by omega) have he : (T+1)^(e+1)≤(T+1)^(e+3) := Nat.pow_le_pow_right hbase (by omega) calc _ ≤ 10000*(T+1)^2+(T+1)*(10000*(T+1)^2+C*(T+1)^e) := by gcongr _ = 10000*(T+1)^2+10000*(T+1)^3+C*(T+1)^(e+1) := by ring _ ≤ 10000*(T+1)^(e+3)+10000*(T+1)^(e+3)+C*(T+1)^(e+3) := by gcongr _ = _ := by ring lemma chargeBound_polynomial {a b : DataType} (p : Expression a b) (T : ℕ) : chargeBound p T≤chargeCoefficient p*(T+1)^chargeDegree p := by induction p with | compose p q ihp ihq | both p q ihp ihq | branch p q ihp ihq => exact monomial_add_bound T _ _ _ _ _ _ ihp ihq | fold p ih => exact monomial_fold_bound T _ _ _ ih | ident | constant | fst | snd | cons | consBit | append | reverse | toList | toBits | toNat | add | sub | mul | less | divRem | query | rank => exact Nat.le_refl _ lemma evaluate_polynomial {n : ℕ} (O : IndependenceOracle n) {a b : DataType} (p : Expression a b) (S : ℕ) (x : Value a) (y : Value b) (c : ℕ) (hs : Safe O S p x) (he : evaluate O p x=some (y,c)) : c≤chargeCoefficient p*(S+n+1)^chargeDegree p := (evaluate_charge O p S x y c hs he).trans (chargeBound_polynomial p (S+n)) lemma foldSafe_mono {A B : Type*} (p q : A×B → Prop) (f : A×B → Option B) (hpq : ∀ x,p x → q x) (xs : List A) (z : B) (h : FoldSafe p f xs z) : FoldSafe q f xs z := by induction xs generalizing z with | nil => trivial | cons x xs ih => exact ⟨hpq _ h.1,fun y hy => ih y (h.2 y hy)⟩ lemma safe_mono {n S T : ℕ} {O : IndependenceOracle n} {a b : DataType} (p : Expression a b) (x : Value a) (h : Safe O S p x) (hST : S≤T) : Safe O T p x := by induction p with | compose p q ihp ihq => exact ⟨h.1.trans hST,fun y hy => (h.2.1 y hy).trans hST, ihp _ h.2.2.1,fun y hy => ihq _ (h.2.2.2 y hy)⟩ | both p q ihp ihq => exact ⟨h.1.trans hST,fun y hy => (h.2.1 y hy).trans hST,ihp _ h.2.2.1,ihq _ h.2.2.2⟩ | branch p q ihp ihq => refine ⟨h.1.trans hST,fun y hy => (h.2.1 y hy).trans hST,?_⟩ rcases x with ⟨v,x⟩ cases v <;> simp only [Bool.false_eq_true,ite_false,ite_true] at * · exact ihp _ h.2.2 · exact ihq _ h.2.2 | fold p ih => exact ⟨h.1.trans hST,fun y hy => (h.2.1 y hy).trans hST, foldSafe_mono _ _ _ (fun x hx => ih x hx) _ _ h.2.2⟩ | _ => exact ⟨h.1.trans hST,fun y hy => (h.2.1 y hy).trans hST,trivial⟩ lemma safe_compose {n S : ℕ} (O : IndependenceOracle n) {a b c : DataType} (p : Expression a b) (q : Expression b c) (x : Value a) (hp : Safe O S p x) (hq : ∀ y,run O p x=some y → Safe O S q y) : Safe O S (.compose p q) x := by refine ⟨safe_input hp,?_,hp,hq⟩ intro z hz simp only [run] at hz cases he : run O p x with | none => simp [he] at hz | some y => simp only [he,Option.bind_some] at hz exact safe_output (hq y he) hz lemma safe_both {n S : ℕ} (O : IndependenceOracle n) {a b c : DataType} (p : Expression a b) (q : Expression a c) (x : Value a) (hp : Safe O S p x) (hq : Safe O S q x) : Safe O (3*S+1) (.both p q) x := by have hS : S≤3*S+1 := by omega refine ⟨(safe_input hp).trans hS,?_,safe_mono p x hp hS,safe_mono q x hq hS⟩ intro z hz simp only [run] at hz cases he : run O p x with | none => simp [he] at hz | some y => simp only [he] at hz cases hf : run O q x with | none => simp [hf] at hz | some w => simp only [hf,] at hz have hh : (y,w)=z := Option.some.inj hz cases hh have hy := safe_output hp he have hw := safe_output hq hf rw [width_pair] omega lemma foldSafe_invariant {A B : Type*} (ok : A×B → Prop) (f : A×B → Option B) (P : B → Prop) (xs : List A) (z : B) (hz : P z) (hstep : ∀ x∈xs,∀ y,P y → ok (x,y) ∧ ∀ y',f (x,y)=some y' → P y') : FoldSafe ok f xs z := by induction xs generalizing z with | nil => trivial | cons x xs ih => obtain ⟨hgood,hnext⟩ := hstep x (by simp) z hz exact ⟨hgood,fun y hy => ih y (hnext y hy) (fun v hv => hstep v (by simp [hv]))⟩ lemma foldValue_invariant {A B : Type*} (f : A×B → Option B) (P : B → Prop) (xs : List A) (z : B) (hz : P z) (hstep : ∀ x∈xs,∀ y,P y → ∀ y',f (x,y)=some y' → P y') (y : B) (hy : foldValue f xs z=some y) : P y := by induction xs generalizing z with | nil => cases hy; exact hz | cons x xs ih => simp only [foldValue] at hy cases he : f (x,z) with | none => simp [he] at hy | some w => simp only [he,Option.bind_some] at hy exact ih w (hstep x (by simp) z hz w he) (fun v hv => hstep v (by simp [hv])) hy lemma safe_fold_invariant {n S : ℕ} (O : IndependenceOracle n) {a b : DataType} (p : Expression (.prod a b) b) (xs : List (Value a)) (z : Value b) (P : Value b → Prop) (hz : P z) (hw : width (a:=.prod (.list a) b) (xs,z)≤S) (hwidth : ∀ y,P y → width y≤S) (hstep : ∀ x∈xs,∀ y,P y → Safe O S p (x,y) ∧ ∀ y',run O p (x,y)=some y' → P y') : Safe O S (.fold p) (xs,z) := by refine ⟨hw,?_,foldSafe_invariant _ _ P xs z hz hstep⟩ intro y hy exact hwidth y (foldValue_invariant _ P xs z hz (fun x hx v hv => (hstep x hx v hv).2) y hy) inductive SizePolynomial where | constant : ℕ → SizePolynomial | input : SizePolynomial | add : SizePolynomial → SizePolynomial → SizePolynomial | mul : SizePolynomial → SizePolynomial → SizePolynomial namespace SizePolynomial def eval : SizePolynomial → ℕ → ℕ | .constant c,_ => c | .input,x => x | .add p q,x => p.eval x+q.eval x | .mul p q,x => p.eval x*q.eval x def degree : SizePolynomial → ℕ | .constant _ => 0 | .input => 1 | .add p q | .mul p q => p.degree+q.degree def coefficient : SizePolynomial → ℕ | .constant c => c | .input => 1 | .add p q => p.coefficient+q.coefficient | .mul p q => p.coefficient*q.coefficient lemma monotone (p : SizePolynomial) : Monotone p.eval := by intro x y h induction p with | constant c => rfl | input => exact h | add p q ihp ihq => exact Nat.add_le_add ihp ihq | mul p q ihp ihq => exact Nat.mul_le_mul ihp ihq lemma bound (p : SizePolynomial) (x : ℕ) : p.eval x≤p.coefficient*(x+1)^p.degree := by induction p with | constant c => simp [eval,coefficient,degree] | input => simp [eval,coefficient,degree] | add p q ihp ihq => have hp := Nat.pow_le_pow_right (by omega : 1≤x+1) (Nat.le_add_right p.degree q.degree) have hq := Nat.pow_le_pow_right (by omega : 1≤x+1) (Nat.le_add_left q.degree p.degree) dsimp only [eval,coefficient,degree] calc _ ≤ p.coefficient*(x+1)^(p.degree+q.degree)+q.coefficient*(x+1)^(p.degree+q.degree) := Nat.add_le_add (ihp.trans (Nat.mul_le_mul_left _ hp)) (ihq.trans (Nat.mul_le_mul_left _ hq)) _ = _ := by ring | mul p q ihp ihq => dsimp only [eval,coefficient,degree] calc _ ≤ (p.coefficient*(x+1)^p.degree)*(q.coefficient*(x+1)^q.degree) := Nat.mul_le_mul ihp ihq _ = _ := by rw [pow_add]; ring def subst : SizePolynomial → SizePolynomial → SizePolynomial | .constant c,_ => .constant c | .input,q => q | .add p r,q => .add (p.subst q) (r.subst q) | .mul p r,q => .mul (p.subst q) (r.subst q) lemma eval_subst (p q : SizePolynomial) (x : ℕ) : (p.subst q).eval x=p.eval (q.eval x) := by induction p <;> simp_all [subst,eval] end SizePolynomial def Controlled {a b : DataType} (p : Expression a b) : Prop := ∃ f : SizePolynomial,∀ {n : ℕ} (O : IndependenceOracle n) (x : Value a),Safe O (f.eval (width x)) p x lemma controlled_input {a b : DataType} {p : Expression a b} (hp : Controlled p) : ∃ C d : ℕ,∀ {n : ℕ} (O : IndependenceOracle n) (S : ℕ) (x : Value a), width x≤S → Safe O (C*(S+1)^d) p x := by obtain ⟨f,hf⟩ := hp exact ⟨f.coefficient,f.degree,fun O S x hx => safe_mono p x (hf O x) ((f.monotone hx).trans (f.bound S))⟩ lemma controlled_compose {a b c : DataType} (p : Expression a b) (q : Expression b c) (hp : Controlled p) (hq : Controlled q) : Controlled (.compose p q) := by obtain ⟨f,hf⟩ := hp obtain ⟨g,hg⟩ := hq refine ⟨.add f (g.subst f),fun O x => ?_⟩ apply safe_compose O p q x · exact safe_mono p x (hf O x) (by simp only [SizePolynomial.eval]; omega) · intro y hy have h := safe_output (hf O x) hy apply safe_mono q y (hg O y) rw [SizePolynomial.eval,SizePolynomial.eval_subst] exact (g.monotone h).trans (Nat.le_add_left _ _) lemma controlled_both {a b c : DataType} (p : Expression a b) (q : Expression a c) (hp : Controlled p) (hq : Controlled q) : Controlled (.both p q) := by obtain ⟨f,hf⟩ := hp obtain ⟨g,hg⟩ := hq refine ⟨.add (.mul (.constant 3) (.add f g)) (.constant 1),fun O x => ?_⟩ apply safe_both O p q x · exact safe_mono p x (hf O x) (Nat.le_add_right _ _) · exact safe_mono q x (hg O x) (Nat.le_add_left _ _) lemma controlled_branch {a b : DataType} (p q : Expression a b) (hp : Controlled p) (hq : Controlled q) : Controlled (.branch p q) := by obtain ⟨f,hf⟩ := hp obtain ⟨g,hg⟩ := hq refine ⟨.add .input (.add f g),fun O x => ?_⟩ rcases x with ⟨v,x⟩ have hw : width x≤width (a:=.prod .bool a) (v,x) := by rw [width_pair]; omega have hp' : Safe O (width (a:=.prod .bool a) (v,x)+ (f.eval (width (a:=.prod .bool a) (v,x))+g.eval (width (a:=.prod .bool a) (v,x)))) p x := safe_mono p x (hf O x) ((f.monotone hw).trans (by omega)) have hq' : Safe O (width (a:=.prod .bool a) (v,x)+ (f.eval (width (a:=.prod .bool a) (v,x))+g.eval (width (a:=.prod .bool a) (v,x)))) q x := safe_mono q x (hg O x) ((g.monotone hw).trans (by omega)) refine ⟨by simp only [SizePolynomial.eval]; omega,?_,?_⟩ · intro y hy cases v · exact safe_output hp' hy · exact safe_output hq' hy · cases v · exact hp' · exact hq' @[simp] lemma width_nat (x : ℕ) : width (a:=.nat) x=x.bits.length := rfl @[simp] lemma width_word (x : Word) : width (a:=.word) x=x.length := rfl @[simp] lemma width_bool (x : Bool) : width (a:=.bool) x=1 := rfl @[simp] lemma width_unit (x : Unit) : width (a:=.unit) x=0 := rfl lemma bits_length_mono {a b : ℕ} (h : a≤b) : a.bits.length≤b.bits.length := by simpa only [Nat.size_eq_bits_len] using Nat.size_le_size h lemma bits_length_le_value (a : ℕ) : a.bits.length≤a := by rw [Nat.size_eq_bits_len] exact Nat.size_le.mpr a.lt_two_pow_self lemma bits_length_add (a b : ℕ) : (a+b).bits.length≤a.bits.length+b.bits.length+1 := by simp only [Nat.size_eq_bits_len] apply Nat.size_le.mpr have ha := Nat.lt_size_self a have hb := Nat.lt_size_self b have hpa : 1≤2^a.size := Nat.one_le_pow _ _ (by decide) have hpb : 1≤2^b.size := Nat.one_le_pow _ _ (by decide) rw [pow_succ,pow_add] nlinarith lemma bits_length_mul (a b : ℕ) : (a*b).bits.length≤a.bits.length+b.bits.length := by simp only [Nat.size_eq_bits_len] apply Nat.size_le.mpr rw [pow_add] calc a*b≤(2^a.size)*b := Nat.mul_le_mul_right _ (Nat.lt_size_self a).le _ < (2^a.size)*(2^b.size) := Nat.mul_lt_mul_of_pos_left (Nat.lt_size_self b) (by positivity) lemma bits_length_binaryValue (x : Word) : (binaryValue x).bits.length≤x.length := by rw [←normalWord_eq_bits] exact normal_length x lemma width_list_bool (x : Word) : width (a:=.list .bool) x=4*x.length := by induction x with | nil => rfl | cons b xs ih => rw [width_cons (a:=.bool),width_bool,ih,List.length_cons] omega lemma width_list_append {a : DataType} (x y : List (Value a)) : width (a:=.list a) (x++y)=width (a:=.list a) x+width (a:=.list a) y := by induction x with | nil => simp | cons z x ih => simp only [List.cons_append,width_cons,ih]; omega lemma width_list_reverse {a : DataType} (x : List (Value a)) : width (a:=.list a) x.reverse=width (a:=.list a) x := by induction x with | nil => rfl | cons z x ih => simp only [List.reverse_cons,width_list_append,width_cons,width_nil,ih]; omega lemma width_list_member {a : DataType} (x : Value a) (xs : List (Value a)) (h : x∈xs) : width x≤width (a:=.list a) xs := by induction xs with | nil => cases h | cons z zs ih => simp only [List.mem_cons] at h cases h with | inl h => subst x; rw [width_cons]; omega | inr h => have hi := ih h; rw [width_cons]; omega def Atomic : {a b : DataType} → Expression a b → Prop | _,_,.compose _ _ | _,_,.both _ _ | _,_,.branch _ _ | _,_,.fold _ => False | _,_,_ => True def constantWidth : {a b : DataType} → Expression a b → ℕ | _,_,.constant x => width x | _,_,_ => 0 lemma safe_atomic {n S : ℕ} (O : IndependenceOracle n) {a b : DataType} (p : Expression a b) (x : Value a) (ha : Atomic p) (hx : width x≤S) (hy : ∀ y,run O p x=some y → width y≤S) : Safe O S p x := by cases p <;> first | contradiction | exact ⟨hx,hy,trivial⟩ lemma atomic_width {n : ℕ} (O : IndependenceOracle n) {a b : DataType} (p : Expression a b) (x : Value a) (ha : Atomic p) (y : Value b) (hy : run O p x=some y) : width y≤8*(width x+constantWidth p+1) := by cases p with | compose | both | branch | fold => contradiction | ident => cases hy; simp only [constantWidth]; omega | constant z => cases hy; simp only [constantWidth]; omega | fst => rcases x with ⟨u,v⟩ cases hy simp only [width_pair,constantWidth]; omega | snd => rcases x with ⟨u,v⟩ cases hy simp only [width_pair,constantWidth]; omega | @cons a => rcases x with ⟨u,v⟩ cases hy rw [width_pair (a := a) (b := .list a)] simp only [width_cons,constantWidth]; omega | consBit => rcases x with ⟨u,v⟩ cases hy rw [width_pair (a := .bool) (b := .word)] simp only [width_word,List.length_cons,width_bool,constantWidth]; omega | append => rcases x with ⟨u,v⟩ cases hy rw [width_pair (a := .word) (b := .word)] simp only [width_word,List.length_append,constantWidth]; omega | reverse => cases hy simp only [width_word,List.length_reverse,constantWidth]; omega | toList => cases hy rw [width_list_bool] simp only [width_word,constantWidth]; omega | toBits => cases hy simp only [width_word,width_nat,constantWidth]; omega | toNat => cases hy have h := bits_length_binaryValue x simp only [width_word,width_nat,constantWidth]; omega | add => rcases x with ⟨u,v⟩ cases hy have h := bits_length_add u v rw [width_pair (a := .nat) (b := .nat)] simp only [width_nat,constantWidth]; omega | mul => rcases x with ⟨u,v⟩ cases hy have h := bits_length_mul u v rw [width_pair (a := .nat) (b := .nat)] simp only [width_nat,constantWidth]; omega | sub => rcases x with ⟨u,v⟩ simp only [run] at hy split_ifs at hy with hv · cases hy have h := bits_length_mono (Nat.sub_le u v) rw [width_pair (a := .nat) (b := .nat)] simp only [width_nat,constantWidth]; omega | less => simp only [width_bool,constantWidth]; omega | divRem => rcases x with ⟨u,v⟩ simp only [run] at hy split_ifs at hy with hv · cases hy have h₁ := bits_length_mono (Nat.mod_le v u) have h₂ := bits_length_mono (Nat.div_le_self v u) simp only [width_pair (a := .nat) (b := .nat),width_nat,constantWidth]; omega | query b => simp only [width_bool,constantWidth]; omega | rank b => simp only [run] at hy split_ifs at hy with hx · cases hy have h₁ := bits_length_binaryValue (rankBits b O x.reverse) have h₂ := rankBits_length O b x.reverse simp only [List.length_reverse] at h₂ simp only [width_nat,width_word,constantWidth,rankWord]; omega lemma controlled_atomic {a b : DataType} (p : Expression a b) (ha : Atomic p) : Controlled p := by refine ⟨.mul (.constant 8) (.add (.add .input (.constant (constantWidth p))) (.constant 1)),fun O x => ?_⟩ apply safe_atomic O p x ha · dsimp [SizePolynomial.eval]; omega · exact fun y hy => atomic_width O p x ha y hy lemma foldSafe_prefix {A B : Type*} (ok : A×B → Prop) (f : A×B → Option B) (xs : List A) (z : B) (h : ∀ pre x post,xs=pre++x::post → ∀ y,foldValue f pre z=some y → ok (x,y)) : FoldSafe ok f xs z := by induction xs generalizing z with | nil => trivial | cons x xs ih => refine ⟨h [] x xs rfl z rfl,?_⟩ intro y hy apply ih y intro pre a post he w hw apply h (x::pre) a post (by simpa using congrArg (List.cons x) he) w simp only [foldValue,hy,Option.bind_some] exact hw lemma controlled_fold {a b : DataType} (p : Expression (.prod a b) b) (hp : Controlled p) (g : SizePolynomial) (hg : ∀ {n : ℕ} (O : IndependenceOracle n) (xs : List (Value a)) (z : Value b) (pre post : List (Value a)),xs=pre++post → ∀ y,foldValue (run O p) pre z=some y → width y≤g.eval (width (a:=.prod (.list a) b) (xs,z))) : Controlled (.fold p) := by obtain ⟨f,hf⟩ := hp let vP : SizePolynomial := .add (.add (.mul (.constant 2) .input) (.constant 1)) g let h : SizePolynomial := .add (.add .input g) (f.subst vP) refine ⟨h,fun O x => ?_⟩ rcases x with ⟨xs,z⟩ have hS : width (a:=.prod (.list a) b) (xs,z)≤h.eval (width (a:=.prod (.list a) b) (xs,z)) := by dsimp [h,SizePolynomial.eval]; omega have hgS : g.eval (width (a:=.prod (.list a) b) (xs,z))≤h.eval (width (a:=.prod (.list a) b) (xs,z)) := by dsimp [h,SizePolynomial.eval]; omega refine ⟨hS,?_,?_⟩ · intro y hy exact (hg O xs z xs [] (by simp) y hy).trans hgS · apply foldSafe_prefix intro pre v post he y hy have hay : width y≤g.eval (width (a:=.prod (.list a) b) (xs,z)) := hg O xs z pre (v::post) he y hy have ha : width (a:=a) v≤width (a:=.prod (.list a) b) (xs,z) := by have hm : v∈xs := by rw [he]; simp have ha := width_list_member v xs hm rw [width_pair]; omega have hinput : width (a:=.prod a b) (v,y)≤vP.eval (width (a:=.prod (.list a) b) (xs,z)) := by rw [width_pair] dsimp [vP,SizePolynomial.eval] omega apply safe_mono p (v,y) (hf O (v,y)) exact (f.monotone hinput).trans (by dsimp only [h,SizePolynomial.eval] rw [SizePolynomial.eval_subst] omega) lemma mod_double_lt (a b : ℕ) (hb : 0 p | k+1,p => gcdSteps k (gcdStep p) lemma gcdSteps_zero (k a : ℕ) : gcdSteps k (a,0)=(a,0) := by induction k with | zero => rfl | succ k ih => simpa [gcdSteps,gcdStep] using ih lemma gcdSteps_done (k a b : ℕ) (hba : b≤a) (hk : a.size+b.size≤k) : gcdSteps k (a,b)=(Nat.gcd a b,0) := by induction k generalizing a b with | zero => have ha : a=0 := Nat.size_eq_zero.mp (by omega) have hb : b=0 := Nat.size_eq_zero.mp (by omega) simp [ha,hb,gcdSteps] | succ k ih => by_cases hb : b=0 · subst b; simp [gcdSteps_zero] · have hb' := Nat.pos_of_ne_zero hb have hl := mod_size_lt a b hb' hba have hs := Nat.size_le_size hba have hh := ih b (a%b) (Nat.le_of_lt (Nat.mod_lt a hb')) (by omega) simp only [gcdSteps,gcdStep,hb,ite_false] rw [hh,Nat.gcd_comm b (a%b),←Nat.gcd_rec,Nat.gcd_comm b a] namespace Expression abbrev NN := DataType.prod .nat .nat def sortPair : Expression NN NN := applyIf less ident swap def gcdStepCode : Expression NN NN := applyIf (snd >>> natEqZero) (both snd (swap >>> natMod)) ident def gcdCode : Expression NN .nat := sortPair >>> both (both (fst >>> toBits) (snd >>> toBits) >>> append >>> toList) ident >>> fold (snd >>> gcdStepCode) >>> fst lemma run_sortPair {n : ℕ} (O : IndependenceOracle n) (a b : ℕ) : run O sortPair (a,b)=some (if a simp [h] lemma run_gcdStepCode {n : ℕ} (O : IndependenceOracle n) (a b : ℕ) : run O gcdStepCode (a,b)=some (gcdStep (a,b)) := by by_cases hb : b=0 <;> simp [gcdStepCode,applyIf,run,swap,natEqZero,natMod,natDivRem,gcdStep,hb] lemma fold_gcdStepCode {n : ℕ} (O : IndependenceOracle n) (xs : List Bool) (p : ℕ × ℕ) : foldValue (run O (snd (a:=.bool) >>> gcdStepCode)) xs p=some (gcdSteps xs.length p) := by induction xs generalizing p with | nil => rfl | cons b xs ih => rcases p with ⟨a,c⟩ change ((run O gcdStepCode (a,c)).bind fun p => foldValue (run O (snd (a:=.bool) >>> gcdStepCode)) xs p)=_ rw [run_gcdStepCode,Option.bind_some,ih] rfl lemma run_gcdCode {n : ℕ} (O : IndependenceOracle n) (a b : ℕ) : run O gcdCode (a,b)=some (Nat.gcd a b) := by unfold gcdCode have hs := run_sortPair O a b simp only [run] rw [hs] simp only [Option.bind_some] by_cases hab : a>> gcdStepCode)) (b.bits++a.bits) (b,a)).bind fun p => some p.1)=some (Nat.gcd a b) rw [fold_gcdStepCode] simp only [List.length_append,Nat.size_eq_bits_len] rw [gcdSteps_done _ _ _ (Nat.le_of_lt hab) (by rfl)] simp [Nat.gcd_comm] · simp only [hab,ite_false] change ((foldValue (run O (snd (a:=.bool) >>> gcdStepCode)) (a.bits++b.bits) (a,b)).bind fun p => some p.1)=some (Nat.gcd a b) rw [fold_gcdStepCode] simp only [List.length_append,Nat.size_eq_bits_len] rw [gcdSteps_done _ _ _ (Nat.le_of_not_gt hab) (by rfl)] rfl end Expression open Expression syntax "control" : tactic macro_rules | `(tactic| control) => `(tactic| first | assumption | apply controlled_compose <;> control | apply controlled_both <;> control | apply controlled_branch <;> control | exact controlled_atomic _ trivial) lemma controlled_onLeft {a b c : DataType} (p : Expression a b) (hp : Controlled p) : Controlled (onLeft (c:=c) p) := by unfold onLeft; control lemma controlled_onRight {a b c : DataType} (p : Expression a b) (hp : Controlled p) : Controlled (onRight (c:=c) p) := by unfold onRight; control lemma controlled_swap {a b : DataType} : Controlled (Expression.swap (a:=a) (b:=b)) := by unfold Expression.swap; control lemma controlled_letIn {a b c : DataType} (p : Expression a b) (q : Expression (.prod a b) c) (hp : Controlled p) (hq : Controlled q) : Controlled (letIn p q) := by unfold letIn; control lemma controlled_applyIf {a b : DataType} (p : Expression a .bool) (q r : Expression a b) (hp : Controlled p) (hq : Controlled q) (hr : Controlled r) : Controlled (applyIf p q r) := by unfold applyIf; control lemma controlled_boolNot : Controlled boolNot := by unfold boolNot; control lemma controlled_boolAnd : Controlled boolAnd := by unfold boolAnd; control lemma controlled_natEqZero : Controlled natEqZero := by unfold natEqZero; control lemma controlled_natSub : Controlled natSub := by unfold natSub; control lemma controlled_natDivRem : Controlled natDivRem := by unfold natDivRem; control lemma controlled_natDiv : Controlled natDiv := by unfold natDiv; control lemma controlled_natMod : Controlled natMod := by unfold natMod; control lemma controlled_listReverse {a : DataType} : Controlled (listReverse (a:=a)) := by unfold listReverse apply controlled_compose · control · apply controlled_fold _ (controlled_atomic (cons (a:=a)) trivial) (.mul (.constant 2) .input) intro n O xs z pre post he y hy have hh := foldValue_eq_foldl (run O (cons (a:=a))) (fun z x => x::z) (fun _ _ => rfl) pre z rw [hh] at hy cases hy rw [List.foldl_flip_cons_eq_append',width_list_append,width_list_reverse] have hp : width (a:=.list a) pre≤width (a:=.list a) xs := by rw [he,width_list_append]; omega rw [width_pair (a:=.list a) (b:=.list a)] dsimp [SizePolynomial.eval] omega lemma foldl_succ {A : Type*} (l : List A) (z : ℕ) : l.foldl (fun z _ => z+1) z=z+l.length := by induction l generalizing z with | nil => simp | cons x xs ih => simp only [List.foldl_cons,ih,List.length_cons]; omega lemma controlled_listLength {a : DataType} : Controlled (listLength (a:=a)) := by unfold listLength apply controlled_compose · control · apply controlled_fold _ (by control) (.mul (.constant 2) .input) intro n O xs z pre post he y hy have hh := foldValue_eq_foldl (run O (both (snd (a:=a)) (constant 1) >>> Expression.add)) (fun z (_ : Value a) => z+1) (fun _ _ => rfl) pre z rw [hh] at hy cases hy have hv := foldl_succ pre z rw [hv,width_nat] have hbits := bits_length_add z pre.length have hlen := bits_length_le_value pre.length have hx := list_length_le_width xs have hp : pre.length≤xs.length := by rw [he,List.length_append]; omega rw [width_pair (a:=.list a) (b:=.nat),width_nat] dsimp [SizePolynomial.eval] omega lemma controlled_wordLength : Controlled wordLength := by exact controlled_compose _ _ (controlled_atomic _ trivial) controlled_listLength lemma gcdSteps_max (k a b : ℕ) : (gcdSteps k (a,b)).1≤ max a b ∧ (gcdSteps k (a,b)).2≤ max a b := by induction k generalizing a b with | zero => exact ⟨Nat.le_max_left _ _,Nat.le_max_right _ _⟩ | succ k ih => by_cases hb : b=0 · simpa [hb,gcdStep,gcdSteps] using ih a 0 · have hi := ih b (a%b) have hle : max b (a%b)≤ max a b := max_le (Nat.le_max_right _ _) ((Nat.mod_le _ _).trans (Nat.le_max_left _ _)) simpa [gcdSteps,gcdStep,hb] using And.intro (hi.1.trans hle) (hi.2.trans hle) lemma controlled_gcdStep : Controlled gcdStepCode := by unfold gcdStepCode; control lemma controlled_gcd : Controlled gcdCode := by unfold gcdCode apply controlled_compose · control · apply controlled_compose · control · apply controlled_compose · apply controlled_fold _ (by control) (.mul (.constant 4) .input) intro n O xs z pre post he y hy rcases z with ⟨a,b⟩ rw [fold_gcdStepCode] at hy cases hy have hh := gcdSteps_max pre.length a b have h₁ := bits_length_mono hh.1 have h₂ := bits_length_mono hh.2 have hm : (max a b).bits.length≤a.bits.length+b.bits.length := by rcases le_total a b with h|h · rw [max_eq_right h]; omega · rw [max_eq_left h]; omega rw [width_pair (a:=.nat) (b:=.nat),width_pair (a:=.list .bool) (b:=.prod .nat .nat), width_pair (a:=.nat) (b:=.nat)] simp only [width_nat,SizePolynomial.eval] omega · control open Expression def PolySafe {a b : DataType} (p : Expression a b) (R : ℕ → Value a → Prop) : Prop := ∃ f : SizePolynomial,∀ {n : ℕ} (O : IndependenceOracle n) (S : ℕ) (x : Value a), R S x → Safe O (f.eval S) p x lemma polySafe_of_controlled {a b : DataType} (p : Expression a b) (hp : Controlled p) (R : ℕ → Value a → Prop) (g : SizePolynomial) (hg : ∀ S x,R S x → width x≤g.eval S) : PolySafe p R := by obtain ⟨f,hf⟩ := hp refine ⟨f.subst g,fun O S x hx => ?_⟩ apply safe_mono p x (hf O x) rw [SizePolynomial.eval_subst] exact f.monotone (hg S x hx) lemma polySafe_mono {a b : DataType} (p : Expression a b) {R Q : ℕ → Value a → Prop} (hp : PolySafe p Q) (h : ∀ S x,R S x → Q S x) : PolySafe p R := by obtain ⟨f,hf⟩ := hp exact ⟨f,fun O S x hx => hf O S x (h S x hx)⟩ lemma polySafe_compose {a b c : DataType} (p : Expression a b) (q : Expression b c) (R : ℕ → Value a → Prop) (Q : ℕ → Value b → Prop) (hp : PolySafe p R) (hq : PolySafe q Q) (h : ∀ {n : ℕ} (O : IndependenceOracle n) S x,R S x → ∀ y,run O p x=some y → Q S y) : PolySafe (p >>> q) R := by obtain ⟨f,hf⟩ := hp obtain ⟨g,hg⟩ := hq refine ⟨.add f g,fun O S x hx => ?_⟩ apply safe_compose O p q x · exact safe_mono p x (hf O S x hx) (Nat.le_add_right _ _) · intro y hy exact safe_mono q y (hg O S y (h O S x hx y hy)) (Nat.le_add_left _ _) lemma polySafe_both {a b c : DataType} (p : Expression a b) (q : Expression a c) (R : ℕ → Value a → Prop) (hp : PolySafe p R) (hq : PolySafe q R) : PolySafe (.both p q) R := by obtain ⟨f,hf⟩ := hp obtain ⟨g,hg⟩ := hq refine ⟨.add (.mul (.constant 3) (.add f g)) (.constant 1),fun O S x hx => ?_⟩ apply safe_both O p q x · exact safe_mono p x (hf O S x hx) (Nat.le_add_right _ _) · exact safe_mono q x (hg O S x hx) (Nat.le_add_left _ _) lemma polySafe_fold {a b : DataType} (p : Expression (.prod a b) b) (R : ℕ → Value (.prod (.list a) b) → Prop) (Q : ℕ → Value (.prod a b) → Prop) (hp : PolySafe p Q) (g : SizePolynomial) (hinput : ∀ S x,R S x → width x≤g.eval S) (hacc : ∀ {n : ℕ} (O : IndependenceOracle n) S xs z,R S (xs,z) → ∀ pre post,xs=pre++post → ∀ y,foldValue (run O p) pre z=some y → width y≤g.eval S) (hstep : ∀ {n : ℕ} (O : IndependenceOracle n) S xs z,R S (xs,z) → ∀ pre x post,xs=pre++x::post → ∀ y,foldValue (run O p) pre z=some y → Q S (x,y)) : PolySafe (.fold p) R := by obtain ⟨f,hf⟩ := hp refine ⟨.add f g,fun O S x hx => ?_⟩ obtain ⟨xs,z⟩ := x refine ⟨(hinput S (xs,z) hx).trans (Nat.le_add_left _ _),?_,?_⟩ · intro y hy exact (hacc O S xs z hx xs [] (by simp) y hy).trans (Nat.le_add_left _ _) · apply foldSafe_prefix intro pre x post he y hy exact safe_mono p (x,y) (hf O S (x,y) (hstep O S xs z hx pre x post he y hy)) (Nat.le_add_right _ _) lemma polySafe_controlled {a b : DataType} (p : Expression a b) (hp : PolySafe p (fun S x => width x≤S)) : Controlled p := by obtain ⟨f,hf⟩ := hp exact ⟨f,fun O x => hf O (width x) x le_rfl⟩ lemma run_mapStep_partial {n : ℕ} (O : IndependenceOracle n) {a b c : DataType} (p : Expression (.prod a c) b) (x : Value a) (zs : List (Value b)) (ctx : Value c) : run O (mapStep p) (x,(zs,ctx))=(run O p (x,ctx)).map (fun v => (v::zs,ctx)) := by simp only [mapStep,run,bind_pure_comp,Option.bind_some] cases he : run O p (x,ctx) <;> simp [he] lemma fold_mapStep_bound {n : ℕ} (O : IndependenceOracle n) {a b c : DataType} (p : Expression (.prod a c) b) (xs : List (Value a)) (zs : List (Value b)) (ctx : Value c) (U : ℕ) (hu : ∀ x∈xs,∀ v,run O p (x,ctx)=some v → width v≤U) (y : Value (.prod (.list b) c)) (hy : foldValue (run O (mapStep p)) xs (zs,ctx)=some y) : width (a:=.list b) y.1≤width (a:=.list b) zs+xs.length*(2*U+2) ∧ y.2=ctx := by induction xs generalizing zs with | nil => cases hy; simp | cons x xs ih => rw [foldValue,run_mapStep_partial] at hy cases he : run O p (x,ctx) with | none => simp [he] at hy | some v => simp only [he,Option.map_some,Option.bind_some] at hy have hv := hu x (by simp) v he have hh := ih (v::zs) (fun x hx => hu x (by simp [hx])) hy rw [width_cons] at hh refine ⟨?_,hh.2⟩ simp only [List.length_cons,Nat.add_mul,Nat.one_mul] omega lemma controlled_mapStep {a b c : DataType} (p : Expression (.prod a c) b) (hp : Controlled p) : Controlled (mapStep p) := by unfold mapStep; control lemma controlled_mapFold {a b c : DataType} (p : Expression (.prod a c) b) (hp : Controlled p) : Controlled (.fold (mapStep p)) := by obtain ⟨f,hf⟩ := hp let s : SizePolynomial := .add (.mul (.constant 3) .input) (.constant 1) let g : SizePolynomial := .mul (.add (.mul (.constant 4) .input) (.constant 3)) (.add (.mul (.constant 2) (f.subst s)) (.constant 3)) apply controlled_fold _ (controlled_mapStep p ⟨f,hf⟩) g intro n O xs z pre post he y hy rcases z with ⟨zs,ctx⟩ let W := width (a:=.prod (.list a) (.prod (.list b) c)) (xs,(zs,ctx)) have hx : width (a:=.list a) xs≤W := by dsimp [W]; rw [width_pair (a:=.list a) (b:=.prod (.list b) c)]; omega have hzs : width (a:=.list b) zs≤W := by dsimp [W]; rw [width_pair (a:=.list a) (b:=.prod (.list b) c),width_pair (a:=.list b) (b:=c)]; omega have hc : width ctx≤W := by dsimp [W]; rw [width_pair (a:=.list a) (b:=.prod (.list b) c),width_pair (a:=.list b) (b:=c)]; omega have hl : pre.length≤W := by have hh := list_length_le_width xs have he' := congrArg List.length he simp only [List.length_append] at he' omega let U := f.eval (3*W+1) have hh := fold_mapStep_bound O p pre zs ctx U (by intro x hxp v hv have hxx : x∈xs := by rw [he]; exact List.mem_append_left post hxp have hxb := (width_list_member x xs hxx).trans hx apply (safe_output (hf O (x,ctx)) hv).trans apply f.monotone rw [width_pair (a:=a) (b:=c)] omega) y hy have hm := Nat.mul_le_mul_right (2*U+2) hl have hy' : width (a:=.list b) y.1≤W+W*(2*U+2) := by omega change width y≤g.eval W have hw : width y=2*width (a:=.list b) y.1+1+width ctx := by obtain ⟨ys,vctx⟩ := y change width (a:=.prod (.list b) c) (ys,vctx)=2*width (a:=.list b) ys+1+width ctx rw [width_pair,show vctx=ctx from hh.2] rw [hw] simp only [g,SizePolynomial.eval,SizePolynomial.eval_subst] change _≤(4*W+3)*(2*U+3) nlinarith lemma controlled_mapWith {a b c : DataType} (p : Expression (.prod a c) b) (hp : Controlled p) : Controlled (mapWith p) := by unfold mapWith apply controlled_compose · control · apply controlled_compose · exact controlled_mapFold p hp · apply controlled_compose · control · exact controlled_listReverse def rationalPair (q : ℚ) : ℕ × ℕ := (q.num.natAbs,q.den) def normalizePair (a b : ℕ) : ℕ × ℕ := if b=0 then (0,1) else (a/Nat.gcd a b,b/Nat.gcd a b) lemma rationalPair_div (a b : ℕ) : rationalPair ((a:ℚ)/(b:ℚ))=normalizePair a b := by have he : (a:ℚ)/(b:ℚ)=mkRat (a:ℤ) b := by simp only [Rat.mkRat_eq_divInt,Rat.divInt_eq_div,Int.cast_natCast] rw [he] by_cases hb : b=0 <;> simp [rationalPair,normalizePair,Rat.num_mkRat,Rat.den_mkRat,hb,Nat.gcd_comm,Int.natAbs_ediv_of_nonneg] lemma rationalPair_value {q : ℚ} (hq : 0≤q) : ((rationalPair q).1:ℚ)/((rationalPair q).2:ℚ)=q := by dsimp [rationalPair] have hnum : 0≤q.num := Rat.num_nonneg.mpr hq have he : (q.num.natAbs:ℚ)=(q.num:ℚ) := by have hnat : (q.num.natAbs:ℤ)=q.num := Int.natAbs_of_nonneg hnum simpa only [Int.cast_natCast] using congrArg (fun z : ℤ => (z:ℚ)) hnat rw [he] exact Rat.num_div_den q lemma rationalPair_den (q : ℚ) : 0<(rationalPair q).2 := q.den_pos namespace Expression lemma run_applyIf {n : ℕ} (O : IndependenceOracle n) {a b : DataType} (p : Expression a .bool) (q r : Expression a b) (x : Value a) : run O (applyIf p q r) x=(run O p x).bind (fun t => if t then run O r x else run O q x) := by simp [applyIf,run,Option.bind_assoc] lemma run_letIn {n : ℕ} (O : IndependenceOracle n) {a b c : DataType} (p : Expression a b) (q : Expression (.prod a b) c) (x : Value a) : run O (letIn p q) x=(run O p x).bind (fun y => run O q (x,y)) := by simp [letIn,run,Option.bind_assoc] def normalizeRat : Expression NN NN := applyIf (snd >>> natEqZero) (letIn gcdCode (both (both snd (fst >>> fst) >>> natDiv) (both snd (fst >>> snd) >>> natDiv))) (constant (0,1)) def ratCross : Expression (.prod NN NN) NN := both (both (fst >>> fst) (snd >>> snd) >>> mul) (both (snd >>> fst) (fst >>> snd) >>> mul) def ratAdd : Expression (.prod NN NN) NN := both (ratCross >>> add) (both (fst >>> snd) (snd >>> snd) >>> mul) >>> normalizeRat def ratMul : Expression (.prod NN NN) NN := both (both (fst >>> fst) (snd >>> fst) >>> mul) (both (fst >>> snd) (snd >>> snd) >>> mul) >>> normalizeRat def ratDiv : Expression (.prod NN NN) NN := ratCross >>> normalizeRat def ratLess : Expression (.prod NN NN) .bool := ratCross >>> less def ratMinOne : Expression NN NN := applyIf (swap >>> less) ident (constant (1,1)) lemma run_normalizeRat {n : ℕ} (O : IndependenceOracle n) (a b : ℕ) : run O normalizeRat (a,b)=some (normalizePair a b) := by rw [normalizeRat,run_applyIf] change ((run O natEqZero b).bind fun t => if t then some (0,1) else _)=_ rw [run_natEqZero] by_cases hb : b=0 · simp [hb,normalizePair] · simp only [hb,decide_false,Option.bind_some,Bool.false_eq_true,ite_false] rw [run_letIn,run_gcdCode] change (do let x ← run O natDiv (Nat.gcd a b,a) let y ← run O natDiv (Nat.gcd a b,b) pure (x,y))=some (normalizePair a b) rw [run_natDiv O _ _,run_natDiv O _ _] simp [normalizePair,hb] lemma run_normalizeRat_pair {n : ℕ} (O : IndependenceOracle n) (a b : ℕ) : run O normalizeRat (a,b)=some (rationalPair ((a:ℚ)/(b:ℚ))) := by rw [rationalPair_div] exact run_normalizeRat O a b lemma run_ratCross {n : ℕ} (O : IndependenceOracle n) (a b c d : ℕ) : run O ratCross ((a,b),(c,d))=some (a*d,c*b) := rfl lemma run_ratAdd_raw {n : ℕ} (O : IndependenceOracle n) (a b c d : ℕ) : run O ratAdd ((a,b),(c,d))=some (normalizePair (a*d+c*b) (b*d)) := by change run O normalizeRat (a*d+c*b,b*d)=_ exact run_normalizeRat O _ _ lemma run_ratMul_raw {n : ℕ} (O : IndependenceOracle n) (a b c d : ℕ) : run O ratMul ((a,b),(c,d))=some (normalizePair (a*c) (b*d)) := by change run O normalizeRat (a*c,b*d)=_ exact run_normalizeRat O _ _ lemma run_ratDiv_raw {n : ℕ} (O : IndependenceOracle n) (a b c d : ℕ) : run O ratDiv ((a,b),(c,d))=some (normalizePair (a*d) (c*b)) := by change run O normalizeRat (a*d,c*b)=_ exact run_normalizeRat O _ _ lemma run_ratAdd {n : ℕ} (O : IndependenceOracle n) (q r : ℚ) (hq : 0≤q) (hr : 0≤r) : run O ratAdd (rationalPair q,rationalPair r)=some (rationalPair (q+r)) := by rw [run_ratAdd_raw,←rationalPair_div] congr 2 conv_rhs => rw [←rationalPair_value hq,←rationalPair_value hr] push_cast have hb : (rationalPair q).2 ≠ 0 := (rationalPair_den q).ne' have hd : (rationalPair r).2 ≠ 0 := (rationalPair_den r).ne' field_simp lemma run_ratMul {n : ℕ} (O : IndependenceOracle n) (q r : ℚ) (hq : 0≤q) (hr : 0≤r) : run O ratMul (rationalPair q,rationalPair r)=some (rationalPair (q*r)) := by rw [run_ratMul_raw,←rationalPair_div] congr 2 conv_rhs => rw [←rationalPair_value hq,←rationalPair_value hr] push_cast ring lemma run_ratDiv {n : ℕ} (O : IndependenceOracle n) (q r : ℚ) (hq : 0≤q) (hr : 0≤r) : run O ratDiv (rationalPair q,rationalPair r)=some (rationalPair (q/r)) := by rw [run_ratDiv_raw,←rationalPair_div] congr 2 conv_rhs => rw [←rationalPair_value hq,←rationalPair_value hr] push_cast simp only [div_eq_mul_inv,mul_inv_rev,inv_inv] ring lemma run_ratLess {n : ℕ} (O : IndependenceOracle n) (q r : ℚ) (hq : 0≤q) (hr : 0≤r) : run O ratLess (rationalPair q,rationalPair r)=some (decide (q rw [←rationalPair_value hq,←rationalPair_value hr] have hb : (0:ℚ)<(rationalPair q).2 := by exact_mod_cast rationalPair_den q have hd : (0:ℚ)<(rationalPair r).2 := by exact_mod_cast rationalPair_den r rw [div_lt_div_iff₀ hb hd] norm_cast lemma run_ratMinOne {n : ℕ} (O : IndependenceOracle n) (q : ℚ) (hq : 0≤q) : run O ratMinOne (rationalPair q)=some (rationalPair (min 1 q)) := by have hv := rationalPair_value hq have hd : (0:ℚ)<(rationalPair q).2 := by exact_mod_cast rationalPair_den q have hcmp : (rationalPair q).2<(rationalPair q).1 ↔ (1:ℚ) rw [←hv,lt_div_iff₀ hd,one_mul] norm_cast by_cases h : 1>> fold (snd >>> p) def iterateNat {a : DataType} (p : Expression a a) : Expression (.prod .nat a) a := onLeft unary >>> iterateWord p def fromList : Expression (.list .bool) .word := both (listReverse) (constant []) >>> fold consBit lemma foldValue_iterate {n : ℕ} (O : IndependenceOracle n) {a : DataType} (p : Expression a a) (f : Value a → Value a) (hp : ∀ x,run O p x=some (f x)) (xs : List Bool) (z : Value a) : foldValue (run O (snd (a:=.bool) >>> p)) xs z=some ((f^[xs.length]) z) := by induction xs generalizing z with | nil => rfl | cons b xs ih => change ((run O p z).bind fun y => foldValue (run O (snd (a:=.bool) >>> p)) xs y)=_ rw [hp,Option.bind_some,ih] rfl lemma run_iterateWord {n : ℕ} (O : IndependenceOracle n) {a : DataType} (p : Expression a a) (f : Value a → Value a) (hp : ∀ x,run O p x=some (f x)) (w : Word) (z : Value a) : run O (iterateWord p) (w,z)=some ((f^[w.length]) z) := by change foldValue (run O (snd (a:=.bool) >>> p)) w z=_ exact foldValue_iterate O p f hp w z lemma run_iterateNat {n : ℕ} (O : IndependenceOracle n) {a : DataType} (p : Expression a a) (f : Value a → Value a) (hp : ∀ x,run O p x=some (f x)) (k : ℕ) (z : Value a) : run O (iterateNat p) (k,z)=some ((f^[k]) z) := by obtain ⟨w,hw,hlen⟩ := run_unary O k simp only [iterateNat,onLeft,run,Option.bind_some] rw [hw] change run O (iterateWord p) (w,z)=_ rw [run_iterateWord O p f hp,hlen] lemma run_fromList {n : ℕ} (O : IndependenceOracle n) (xs : List Bool) : run O fromList xs=some xs := by simp only [fromList,run] rw [run_listReverse] change foldValue (run O consBit) xs.reverse []=some xs have hh := foldValue_eq_foldl (run O consBit) (fun z x => x::z) (fun _ _ => rfl) xs.reverse [] simpa using hh def rangeStepCode : Expression (.prod .nat (.list .nat)) (.prod .nat (.list .nat)) := both (both fst (constant 1) >>> add) (both fst snd >>> cons) def rangeCode : Expression .nat (.list .nat) := both ident (constant (0,[])) >>> iterateNat rangeStepCode >>> snd >>> listReverse def rangeStep (p : ℕ × List ℕ) : ℕ × List ℕ := (p.1+1,p.1::p.2) lemma rangeStep_iterate (k : ℕ) : (rangeStep^[k]) (0,[])=(k,(List.range k).reverse) := by induction k with | zero => rfl | succ k ih => rw [Function.iterate_succ_apply',ih]; simp [rangeStep,List.range_succ] lemma run_rangeCode {n : ℕ} (O : IndependenceOracle n) (k : ℕ) : run O rangeCode k=some (List.range k) := by have hh := run_iterateNat O rangeStepCode rangeStep (fun _ => rfl) k (0,[]) change ((run O (iterateNat rangeStepCode) (k,(0,[]))).bind fun p => run O listReverse p.2)=_ rw [hh,rangeStep_iterate,Option.bind_some,run_listReverse,List.reverse_reverse] abbrev SplitState (a : DataType) := DataType.prod .nat (.prod (.list a) (.list a)) def splitStep {a : DataType} : Expression (.prod a (SplitState a)) (SplitState a) := applyIf (snd >>> fst >>> natEqZero) (both (both (snd >>> fst) (constant 1) >>> natSub) (both (both fst (snd >>> snd >>> fst) >>> cons) (snd >>> snd >>> snd))) (both (snd >>> fst) (both (snd >>> snd >>> fst) (both fst (snd >>> snd >>> snd) >>> cons))) def splitAtCode {a : DataType} : Expression (.prod (.list a) .nat) (.prod (.list a) (.list a)) := both fst (both snd (constant ([],[]))) >>> fold splitStep >>> snd >>> both (fst >>> listReverse) (snd >>> listReverse) def takeCode {a : DataType} : Expression (.prod (.list a) .nat) (.list a) := splitAtCode >>> fst def dropCode {a : DataType} : Expression (.prod (.list a) .nat) (.list a) := splitAtCode >>> snd def splitStepValue {a : DataType} (p : Value a × (ℕ × (List (Value a) × List (Value a)))) := if p.2.1=0 then (0,(p.2.2.1,p.1::p.2.2.2)) else (p.2.1-1,(p.1::p.2.2.1,p.2.2.2)) lemma run_splitStep {n : ℕ} (O : IndependenceOracle n) {a : DataType} (x : Value a) (k : ℕ) (u v : List (Value a)) : run O splitStep (x,(k,(u,v)))=some (splitStepValue (x,(k,(u,v)))) := by rw [splitStep,run_applyIf] change ((run O natEqZero k).bind fun t => if t then _ else _)=_ rw [run_natEqZero] by_cases hk : k=0 · subst k; rfl · simp only [hk,decide_false,Option.bind_some,Bool.false_eq_true,ite_false] change ((run O natSub (k,1)).bind fun j => some (j,(x::u,v)))=_ rw [run_natSub] simp [splitStepValue,hk] lemma fold_splitStep {n : ℕ} (O : IndependenceOracle n) {a : DataType} (xs : List (Value a)) (k : ℕ) (u v : List (Value a)) : foldValue (run O splitStep) xs (k,(u,v))= some (k-xs.length,((xs.take k).reverse++u,(xs.drop k).reverse++v)) := by induction xs generalizing k u v with | nil => simp [foldValue] | cons x xs ih => rw [foldValue,run_splitStep] cases k with | zero => simpa [splitStepValue,List.append_assoc] using ih 0 u (x::v) | succ k => simpa [splitStepValue,List.append_assoc] using ih k (x::u) v lemma run_splitAtCode {n : ℕ} (O : IndependenceOracle n) {a : DataType} (xs : List (Value a)) (k : ℕ) : run O splitAtCode (xs,k)=some (xs.take k,xs.drop k) := by change ((foldValue (run O splitStep) xs (k,([],[]))).bind fun p => do let x ← run O listReverse p.2.1 let y ← run O listReverse p.2.2 pure (x,y))=_ rw [fold_splitStep] simp only [List.append_nil,Option.bind_some] rw [run_listReverse,run_listReverse] simp lemma run_takeCode {n : ℕ} (O : IndependenceOracle n) {a : DataType} (xs : List (Value a)) (k : ℕ) : run O takeCode (xs,k)=some (xs.take k) := by change ((run O splitAtCode (xs,k)).bind fun p => some p.1)=_ rw [run_splitAtCode]; rfl lemma run_dropCode {n : ℕ} (O : IndependenceOracle n) {a : DataType} (xs : List (Value a)) (k : ℕ) : run O dropCode (xs,k)=some (xs.drop k) := by change ((run O splitAtCode (xs,k)).bind fun p => some p.2)=_ rw [run_splitAtCode]; rfl lemma run_compose {n : ℕ} (O : IndependenceOracle n) {a b c : DataType} (p : Expression a b) (q : Expression b c) (x : Value a) : run O (p >>> q) x=(run O p x).bind (run O q) := rfl lemma run_both {n : ℕ} (O : IndependenceOracle n) {a b c : DataType} (p : Expression a b) (q : Expression a c) (x : Value a) : run O (both p q) x=(run O p x).bind (fun y => (run O q x).map (fun z => (y,z))) := by simp only [run] congr 1 funext y cases run O q x <;> rfl def headD {a} : Expression (.prod (.list a) a) a := onLeft listReverse >>> fold fst def getDCode {a} : Expression (.prod (.prod (.list a) .nat) a) a := both (fst >>> dropCode) snd >>> headD def boolOr : Expression (.prod .bool .bool) .bool := branch ident (constant true) def natEqual : Expression NN .bool := both less (swap >>> less) >>> boolOr >>> boolNot def listAll : Expression (.list .bool) .bool := both ident (constant true) >>> fold boolAnd def filterStep {a b} (p : Expression (.prod a b) .bool) : Expression (.prod a (.prod (.list a) b)) (.prod (.list a) b) := both (applyIf (both fst (snd >>> snd) >>> p) (snd >>> fst) (both fst (snd >>> fst) >>> cons)) (snd >>> snd) def filterWith {a b} (p : Expression (.prod a b) .bool) : Expression (.prod (.list a) b) (.list a) := both fst (both (constant []) snd) >>> fold (filterStep p) >>> fst >>> listReverse def foldLast {A : Type*} : List A → A → A | [],d => d | x::xs,_ => foldLast xs x lemma foldLast_append {A : Type*} (xs ys : List A) (d : A) : foldLast (xs++ys) d=foldLast ys (foldLast xs d) := by induction xs generalizing d with | nil => rfl | cons x xs ih => exact ih x lemma foldLast_reverse {A : Type*} (xs : List A) (d : A) : foldLast xs.reverse d=xs.headD d := by cases xs with | nil => rfl | cons x xs => simp [List.reverse_cons,foldLast_append,foldLast] lemma run_headD {n : ℕ} (O : IndependenceOracle n) {a} (xs : List (Value a)) (d : Value a) : run O headD (xs,d)=some (xs.headD d) := by have hf : ∀ (ys : List (Value a)) (z : Value a), foldValue (run O (fst (b:=a))) ys z=some (foldLast ys z) := by intro ys induction ys with | nil => intro z; rfl | cons y ys ih => intro z; exact ih y simp only [headD,onLeft,run,run_listReverse] change foldValue (run O (fst (b:=a))) xs.reverse d=_ rw [hf,foldLast_reverse] lemma run_getDCode {n : ℕ} (O : IndependenceOracle n) {a} (xs : List (Value a)) (k : ℕ) (d : Value a) : run O getDCode ((xs,k),d)=some (xs.getD k d) := by simp [getDCode,run] rw [run_dropCode O xs k] change run O headD (xs.drop k,d)=_ rw [run_headD] congr 1 induction k generalizing xs with | zero => cases xs <;> rfl | succ k ih => cases xs with | nil => rfl | cons x xs => exact ih xs lemma run_boolOr {n : ℕ} (O : IndependenceOracle n) (x y : Bool) : run O boolOr (x,y)=some (x||y) := by cases x <;> rfl lemma run_natEqual {n : ℕ} (O : IndependenceOracle n) (x y : ℕ) : run O natEqual (x,y)=some (decide (x=y)) := by simp [natEqual,run,swap] rw [run_boolOr] simp only [Option.bind_some] congr 1 by_cases h : x=y · subst y; simp · have hn : x simp [h,hh] lemma run_listAll {n : ℕ} (O : IndependenceOracle n) (xs : List Bool) : run O listAll xs=some (xs.all id) := by have hf : ∀ (ys : List Bool) (z : Bool), foldValue (run O boolAnd) ys z=some (z && ys.all id) := by intro ys induction ys with | nil => intro z; cases z <;> rfl | cons y ys ih => intro z change ((run O boolAnd (y,z)).bind (foldValue (run O boolAnd) ys))=_ rw [run_boolAnd,Option.bind_some,ih] cases z <;> cases y <;> simp change foldValue (run O boolAnd) xs true=_ simpa using hf xs true lemma run_filterStep {n : ℕ} (O : IndependenceOracle n) {a b} (p : Expression (.prod a b) .bool) (f : Value a → Value b → Bool) (hp : ∀ x z,run O p (x,z)=some (f x z)) (x : Value a) (ys : List (Value a)) (z : Value b) : run O (filterStep p) (x,(ys,z))=some ((if f x z then x::ys else ys),z) := by simp only [filterStep,run_both,run_applyIf] change ((run O p (x,z)).bind fun t => if t then some (x::ys) else some ys).bind (fun v => (some z).map (fun w => (v,w)))=_ rw [hp] cases f x z <;> rfl lemma run_filterWith {n : ℕ} (O : IndependenceOracle n) {a b} (p : Expression (.prod a b) .bool) (f : Value a → Value b → Bool) (hp : ∀ x z,run O p (x,z)=some (f x z)) (xs : List (Value a)) (z : Value b) : run O (filterWith p) (xs,z)=some (xs.filter (fun x => f x z)) := by have hf : ∀ (ys acc : List (Value a)), foldValue (run O (filterStep p)) ys (acc,z)=some ((ys.filter (fun x => f x z)).reverse++acc,z) := by intro ys induction ys with | nil => intro acc; rfl | cons y ys ih => intro acc rw [foldValue,run_filterStep O p f hp,Option.bind_some] cases h : f y z <;> simp [h,ih,List.append_assoc] change ((foldValue (run O (filterStep p)) xs ([],z)).bind fun yz => run O listReverse yz.1)=_ rw [hf] change run O listReverse ((xs.filter (fun x => f x z)).reverse++[])=_ rw [List.append_nil,run_listReverse,List.reverse_reverse] def powStepCode : Expression (.prod .nat .nat) (.prod .nat .nat) := both fst mul def powCode : Expression NN .nat := both snd (both fst (constant 1)) >>> iterateNat powStepCode >>> snd lemma run_powCode {n : ℕ} (O : IndependenceOracle n) (a k : ℕ) : run O powCode (a,k)=some (a^k) := by let f : ℕ×ℕ → ℕ×ℕ := fun z => (z.1,z.1*z.2) have hi : ∀ j v,(f^[j]) (a,v)=(a,a^j*v) := by intro j induction j with | zero => intro v; simp [f] | succ j ih => intro v; rw [Function.iterate_succ_apply',ih]; simp [f,pow_succ]; ring have hh := run_iterateNat O powStepCode f (fun _ => rfl) k (a,1) simp [powCode,run,hh,hi] def ratPowCode : Expression (.prod NN .nat) NN := both (both (fst >>> fst) snd >>> powCode) (both (fst >>> snd) snd >>> powCode) >>> normalizeRat lemma run_ratPowCode {n : ℕ} (O : IndependenceOracle n) (q : ℚ) (hq : 0≤q) (k : ℕ) : run O ratPowCode (rationalPair q,k)=some (rationalPair (q^k)) := by simp [ratPowCode,run] rw [run_powCode O _ _,run_powCode O _ _] change run O normalizeRat ((rationalPair q).1^k,(rationalPair q).2^k)=_ rw [run_normalizeRat_pair] congr 2 conv_rhs => rw [←rationalPair_value hq] push_cast rw [div_pow] end Expression open Expression lemma width_take {a : DataType} (xs : List (Value a)) (k : ℕ) : width (a:=.list a) (xs.take k)≤width (a:=.list a) xs := by have hh := width_list_append (xs.take k) (xs.drop k) rw [List.take_append_drop] at hh omega lemma width_drop {a : DataType} (xs : List (Value a)) (k : ℕ) : width (a:=.list a) (xs.drop k)≤width (a:=.list a) xs := by have hh := width_list_append (xs.take k) (xs.drop k) rw [List.take_append_drop] at hh omega lemma controlled_fromList : Controlled fromList := by unfold fromList apply controlled_compose · exact controlled_both _ _ controlled_listReverse (controlled_atomic _ trivial) · apply controlled_fold consBit (controlled_atomic _ trivial) (.mul (.constant 2) .input) intro n O xs z pre post he y hy have hh := foldValue_eq_foldl (run O consBit) (fun z x => x::z) (fun _ _ => rfl) pre z rw [hh] at hy cases hy rw [List.foldl_flip_cons_eq_append',width_word,List.length_append,List.length_reverse] have hp : pre.length≤xs.length := by rw [he,List.length_append]; omega rw [width_pair (a:=.list .bool) (b:=.word),width_list_bool,width_word] dsimp [SizePolynomial.eval] omega lemma controlled_splitStep {a : DataType} : Controlled (splitStep (a:=a)) := by unfold splitStep; control lemma controlled_splitFold {a : DataType} : Controlled (.fold (splitStep (a:=a))) := by apply controlled_fold splitStep controlled_splitStep (.mul (.constant 8) .input) intro n O xs z pre post he y hy rcases z with ⟨k,u,v⟩ rw [fold_splitStep] at hy cases hy have hpre : width (a:=.list a) pre≤width (a:=.list a) xs := by rw [he,width_list_append]; omega have ht := width_take (a:=a) pre k have hd := width_drop (a:=a) pre k have hk := bits_length_mono (Nat.sub_le k pre.length) simp only [width_pair (a:=.nat) (b:=.prod (.list a) (.list a)), width_pair (a:=.list a) (b:=.list a),width_nat,width_list_append,width_list_reverse, width_pair (a:=.list a) (b:=SplitState a),SizePolynomial.eval] omega lemma controlled_splitAt {a : DataType} : Controlled (splitAtCode (a:=a)) := by have hf := controlled_splitFold (a:=a) have hr := controlled_listReverse (a:=a) unfold splitAtCode control lemma controlled_take {a : DataType} : Controlled (takeCode (a:=a)) := controlled_compose _ _ controlled_splitAt (controlled_atomic _ trivial) lemma controlled_drop {a : DataType} : Controlled (dropCode (a:=a)) := controlled_compose _ _ controlled_splitAt (controlled_atomic _ trivial) lemma fold_fst_mem {A : Type*} (xs : List A) (z y : A) (hy : foldValue (fun p : A×A => some p.1) xs z=some y) : y=z ∨ y∈xs := by induction xs generalizing z with | nil => cases hy; exact Or.inl rfl | cons x xs ih => change foldValue (fun p : A×A => some p.1) xs x=some y at hy rcases ih x hy with h|h · exact Or.inr (by simp [h]) · exact Or.inr (by simp [h]) lemma controlled_headD {a : DataType} : Controlled (headD (a:=a)) := by unfold headD apply controlled_compose · exact controlled_onLeft _ controlled_listReverse · apply controlled_fold (Expression.fst (a:=a) (b:=a)) (controlled_atomic _ trivial) (.mul (.constant 2) .input) intro n O xs z pre post he y hy have hh := fold_fst_mem pre z y hy have hw : width y≤width z+width (a:=.list a) xs := by rcases hh with hh|hh · subst y; omega · have hm : y∈xs := by rw [he]; exact List.mem_append_left post hh have hb := width_list_member y xs hm omega rw [width_pair (a:=.list a) (b:=a)] dsimp [SizePolynomial.eval] omega lemma controlled_getD {a : DataType} : Controlled (getDCode (a:=a)) := by have hd := controlled_drop (a:=a) have hh := controlled_headD (a:=a) unfold getDCode control lemma controlled_boolOr : Controlled boolOr := by unfold boolOr; control lemma controlled_natEqual : Controlled natEqual := by unfold natEqual; control lemma controlled_listAll : Controlled listAll := by unfold listAll apply controlled_compose · control · apply controlled_fold boolAnd controlled_boolAnd (.add .input (.constant 1)) intro n O xs z pre post he y hy simp only [width_bool,SizePolynomial.eval] omega open Expression def wordDouble (w : Word) (b : Bool) : Word := if b then false::(w++w) else w++w lemma wordDouble_length_le (w : Word) (b : Bool) : w.length≤(wordDouble w b).length := by cases b <;> simp [wordDouble,List.length_append] ; omega lemma wordDouble_fold_length_le (xs : List Bool) (z : Word) : z.length≤(xs.foldl wordDouble z).length := by induction xs generalizing z with | nil => rfl | cons b xs ih => exact (wordDouble_length_le z b).trans (ih (wordDouble z b)) lemma wordDouble_prefix_length_le (pre post : List Bool) (z : Word) : (pre.foldl wordDouble z).length≤((pre++post).foldl wordDouble z).length := by rw [List.foldl_append] exact wordDouble_fold_length_le post _ lemma fold_wordDouble {n : ℕ} (O : IndependenceOracle n) (xs : List Bool) (z : Word) : foldValue (run O wordRepeatStep) xs z=some (xs.foldl wordDouble z) := by apply foldValue_eq_foldl intro b w exact run_wordRepeatStep O b w lemma controlled_wordRepeatStep : Controlled wordRepeatStep := by unfold wordRepeatStep; control lemma polySafe_wordRepeatFold : PolySafe (.fold wordRepeatStep) (fun S x => x.1.length≤S ∧ (x.1.foldl wordDouble x.2).length≤S) := by apply polySafe_fold wordRepeatStep _ (fun S x => width x≤5*S+4) (polySafe_of_controlled wordRepeatStep controlled_wordRepeatStep _ (.add (.mul (.constant 5) .input) (.constant 4)) (by intros; assumption)) (.add (.mul (.constant 10) .input) (.constant 4)) · intro S x hx obtain ⟨xs,z⟩ := x dsimp only [Prod.fst,Prod.snd] at hx have hh := wordDouble_fold_length_le xs z rw [width_pair (a:=.list .bool) (b:=.word),width_list_bool,width_word] dsimp [SizePolynomial.eval] omega · intro n O S xs z hx pre post he y hy dsimp only [Prod.fst,Prod.snd] at hx rw [fold_wordDouble] at hy cases hy have hh := wordDouble_prefix_length_le pre post z rw [←he] at hh rw [width_word] dsimp [SizePolynomial.eval] omega · intro n O S xs z hx pre b post he y hy dsimp only [Prod.fst,Prod.snd] at hx rw [fold_wordDouble] at hy cases hy have hh := wordDouble_prefix_length_le pre (b::post) z rw [←he] at hh rw [width_pair (a:=.bool) (b:=.word),width_bool,width_word] omega lemma polySafe_unary : PolySafe unary (fun S x => x≤S) := by unfold unary apply polySafe_compose _ _ _ _ (polySafe_of_controlled _ (by control) _ .input (by intro S x hx exact (bits_length_le_value x).trans hx)) polySafe_wordRepeatFold intro n O S x hx y hy cases hy obtain ⟨w,hw,hlen⟩ := unary_value O x.bits [] rw [fold_wordDouble] at hw have hwe : (x.bits.reverse.foldl wordDouble [])=w := Option.some.inj hw refine ⟨?_,?_⟩ · simpa only [List.length_reverse] using (bits_length_le_value x).trans hx · rw [hwe,hlen] simpa only [List.length_nil,mul_zero,zero_add,binaryValue_bits] using hx abbrev StateData := DataType.prod .word .word def representedState (n : ℕ) (p : Word×Word) : Set (Fin n⊕Fin n) := {i | Sum.elim (fun j => j∈wordSet n p.1) (fun j => j∈wordSet n p.2) i} @[simp] lemma representedState_inl (n : ℕ) (p : Word×Word) (i : Fin n) : Sum.inl i∈representedState n p ↔ p.1[i.val]?.getD false=true := Iff.rfl @[simp] lemma representedState_inr (n : ℕ) (p : Word×Word) (i : Fin n) : Sum.inr i∈representedState n p ↔ p.2[i.val]?.getD false=true := Iff.rfl @[simp] lemma representedState_preinl (n : ℕ) (p : Word×Word) : Sum.inl ⁻¹' representedState n p=wordSet n p.1 := rfl @[simp] lemma representedState_preinr (n : ℕ) (p : Word×Word) : Sum.inr ⁻¹' representedState n p=wordSet n p.2 := rfl lemma wordSet_not {n : ℕ} (x : Word) (hx : x.length=n) : wordSet n (x.map Bool.not)=(wordSet n x)ᶜ := by ext i simp only [wordSet,Set.mem_ofPred_eq,Set.mem_compl_iff] have hi : i.val simp namespace Expression def wordGet : Expression (.prod .word .nat) .bool := both (both (fst >>> toList) snd) (constant false) >>> getDCode def wordNot : Expression .word .word := toList >>> both ident (constant (b:=.unit) ()) >>> mapWith (c:=.unit) (fst >>> boolNot) >>> fromList def wordCountStep : Expression (.prod .bool .nat) .nat := branch ident (both ident (constant 1) >>> add) def wordCount : Expression .word .nat := toList >>> both ident (constant 0) >>> fold wordCountStep lemma run_wordGet {n : ℕ} (O : IndependenceOracle n) (x : Word) (j : ℕ) : run O wordGet (x,j)=some (x[j]?.getD false) := by change run O (getDCode (a:=.bool)) ((x,j),false)=_ exact run_getDCode O (a:=.bool) x j false lemma run_wordNot {n : ℕ} (O : IndependenceOracle n) (x : Word) : run O wordNot x=some (x.map Bool.not) := by change ((run O (mapWith (c:=.unit) (fst >>> boolNot)) (x,())).bind (run O fromList))=_ rw [run_mapWith O _ (fun b (_ : Unit) => !b) (by intro b z; exact run_boolNot O b)] change run O fromList (x.map Bool.not)=_ exact run_fromList O _ lemma run_wordCount {n : ℕ} (O : IndependenceOracle n) (x : Word) : run O wordCount x=some (x.count true) := by have hf : ∀ (xs : Word) k,foldValue (run O wordCountStep) xs k=some (k+xs.count true) := by intro xs induction xs with | nil => intro k; simp [foldValue] | cons b xs ih => intro k cases b with | false => change foldValue (run O wordCountStep) xs k=some (k+(false::xs).count true) rw [ih]; simp | true => change foldValue (run O wordCountStep) xs (k+1)=some (k+(true::xs).count true) rw [ih]; simp [Nat.add_comm,Nat.add_left_comm] change foldValue (run O wordCountStep) x 0=_ simpa using hf x 0 def deficiencyCode : Expression (.prod .nat StateData) .nat := both (both (snd >>> fst >>> wordLength) fst >>> add) (both (both (snd >>> fst >>> rank false) (snd >>> snd >>> wordCount) >>> add) (snd >>> snd >>> wordNot >>> rank true) >>> add) >>> natSub lemma run_deficiencyCode {n : ℕ} (O : IndependenceOracle n) (r : ℕ) (x y : Word) (hx : x.length=n) (hy : y.length=n) : run O deficiencyCode (r,(x,y))= some (n+r-(rankWord O false x+y.count true+rankWord O true (y.map Bool.not))) := by simp only [deficiencyCode,run_compose,run_both] simp [run,run_wordLength,run_wordCount,run_wordNot,hx,hy] rw [run_natSub] end Expression open scoped Classical in lemma deficiencyCode_source {n : ℕ} (M₁ M₂ : Matroid (Fin n)) (O : IndependenceOracle n) (hO : ExactOracles M₁ M₂ O) (hE₁ : M₁.E=Set.univ) (hE₂ : M₂.E=Set.univ) (r : ℕ) (x y : Word) (hx : x.length=n) (hy : y.length=n) : run O Expression.deficiencyCode (r,(x,y))=some (oracleDeficiency n r O (representedState n (x,y))) := by rw [Expression.run_deficiencyCode O r x y hx hy] unfold oracleDeficiency pairedDeficiencyOracle rw [representedState_preinl,representedState_preinr, rankWord_eq_rankOracle M₁ M₂ O hO hE₁ hE₂ false x hx, rankWord_eq_rankOracle M₁ M₂ O hO hE₁ hE₂ true (y.map Bool.not) (by simpa using hy), wordSet_not y hy] rw [Set.toFinset_compl] have hc : (wordSet n y).toFinset.card=y.count true := by simpa using wordSet_card y hy simp only [hc] abbrev Optional (a : DataType) := DataType.prod .bool a abbrev RandomRows := DataType.list .word def optionData {a : DataType} (d : Value a) : Option (Value a) → Value (Optional a) | none => (false,d) | some x => (true,x) lemma foldValue_append {A B : Type*} (f : A×B → Option B) (xs ys : List A) (z : B) : foldValue f (xs++ys) z=(foldValue f xs z).bind (foldValue f ys) := by induction xs generalizing z with | nil => rfl | cons x xs ih => simp only [List.cons_append,foldValue,ih,Option.bind_assoc] namespace Expression @[simp] lemma run_ident {n : ℕ} (O : IndependenceOracle n) {a : DataType} (x : Value a) : run O (ident (a:=a)) x=some x := rfl @[simp] lemma run_fst {n : ℕ} (O : IndependenceOracle n) {a b : DataType} : run O (fst (a:=a) (b:=b))=(fun x => some x.1) := rfl @[simp] lemma run_snd {n : ℕ} (O : IndependenceOracle n) {a b : DataType} : run O (snd (a:=a) (b:=b))=(fun x => some x.2) := rfl @[simp] lemma run_constant {n : ℕ} (O : IndependenceOracle n) {a b : DataType} (x : Value a) (y : Value b) : run O (constant (a:=a) (b:=b) y) x=some y := rfl @[simp] lemma run_reverse {n : ℕ} (O : IndependenceOracle n) (x : Word) : run O reverse x=some x.reverse := rfl @[simp] lemma run_toNat {n : ℕ} (O : IndependenceOracle n) (x : Word) : run O toNat x=some (binaryValue x) := rfl @[simp] lemma run_less {n : ℕ} (O : IndependenceOracle n) (x y : ℕ) : run O less (x,y)=some (decide (x>> takeCode >>> fromList def wordDrop : Expression (.prod .word .nat) .word := onLeft toList >>> dropCode >>> fromList lemma run_wordTake {n : ℕ} (O : IndependenceOracle n) (x : Word) (k : ℕ) : run O wordTake (x,k)=some (x.take k) := by change ((run O (takeCode (a:=.bool)) (x,k)).bind (run O fromList))=_ rw [run_takeCode]; exact run_fromList O _ lemma run_wordDrop {n : ℕ} (O : IndependenceOracle n) (x : Word) (k : ℕ) : run O wordDrop (x,k)=some (x.drop k) := by change ((run O (dropCode (a:=.bool)) (x,k)).bind (run O fromList))=_ rw [run_dropCode]; exact run_fromList O _ abbrev RejectState := DataType.prod NN (Optional .nat) def rejectStep : Expression (.prod .word RejectState) RejectState := both (snd >>> fst) (letIn (both fst (snd >>> fst >>> snd) >>> wordTake >>> reverse >>> toNat) (applyIf (both snd (fst >>> snd >>> fst >>> fst) >>> less) (fst >>> snd >>> snd) (both (constant true) snd))) def rejectCode : Expression (.prod RandomRows NN) (Optional .nat) := both (fst >>> listReverse) (both snd (constant (false,0))) >>> fold rejectStep >>> snd def rejectValue (v k : ℕ) : List Word → Option ℕ | [] => none | x::xs => let z := binaryValue (x.take k).reverse if z simp [run,h] lemma fold_reject {n : ℕ} (O : IndependenceOracle n) (v k : ℕ) (xs : List Word) (z : Bool×ℕ) : foldValue (run O rejectStep) xs.reverse ((v,k),z)= some ((v,k),match rejectValue v k xs with | none => z | some y => (true,y)) := by induction xs with | nil => rfl | cons x xs ih => rw [List.reverse_cons,foldValue_append,ih] simp only [Option.bind_some,foldValue] rw [run_rejectStep] simp only [Option.bind_some] change _=some ((v,k),match rejectValue v k (x::xs) with | none => z | some y => (true,y)) simp only [rejectValue] split_ifs <;> rfl lemma run_rejectCode {n : ℕ} (O : IndependenceOracle n) (xs : List Word) (v k : ℕ) : run O rejectCode (xs,(v,k))=some (optionData 0 (rejectValue v k xs)) := by simp only [rejectCode,run_compose,run_both,run_fst,run_snd,run_constant,Option.bind_some, run_listReverse,Option.map_some] change ((foldValue (run O rejectStep) xs.reverse ((v,k),(false,0))).bind fun z => some z.2)=_ rw [fold_reject] cases rejectValue v k xs <;> rfl end Expression lemma binaryValue_ofFn_reverse (h : ℕ) (bits : BitWord h) : binaryValue (List.ofFn bits).reverse=(wordEquiv h bits).val := by induction h with | zero => simp [wordEquiv,binaryValue] | succ h ih => rw [List.ofFn_succ,List.reverse_cons,binaryValue_append] simp only [List.length_reverse,List.length_ofFn,ih,binaryValue] simp [wordEquiv,Equiv.trans_apply,Fin.consEquiv,finProdFinEquiv,finTwoEquiv] cases bits 0 <;> simp <;> rfl lemma ofFn_bitPrefix (h H : ℕ) (hh : h≤H) (bits : BitWord H) : List.ofFn (bitPrefix h H hh bits)=(List.ofFn bits).take h := by apply List.ext_getElem · simp; omega · intro i hi hj simp [bitPrefix] lemma rejectValue_ofFn (v h D : ℕ) (bits : Fin D → BitWord h) : Expression.rejectValue v h (List.ofFn (fun i => List.ofFn (bits i)))= (boundedUniform v h D bits).map Fin.val := by induction D with | zero => rfl | succ D ih => rw [List.ofFn_succ] simp only [Expression.rejectValue] rw [List.take_of_length_le (by simp),binaryValue_ofFn_reverse] simp only [boundedUniform] split_ifs <;> first | rfl | exact ih (Fin.tail bits) lemma rejectValue_prefix (v h H D : ℕ) (hh : h≤H) (bits : Fin D → BitWord H) : Expression.rejectValue v h (List.ofFn (fun i => List.ofFn (bits i)))= (boundedUniform v h D (fun i => bitPrefix h H hh (bits i))).map Fin.val := by induction D with | zero => rfl | succ D ih => rw [List.ofFn_succ] simp only [Expression.rejectValue,←ofFn_bitPrefix h H hh,binaryValue_ofFn_reverse,boundedUniform] split_ifs <;> first | rfl | exact ih (Fin.tail bits) abbrev BankData := DataType.list RandomRows abbrev Bank := List (List Word) lemma rejectValue_lt (v h : ℕ) (xs : List Word) {i : ℕ} (hi : Expression.rejectValue v h xs=some i) : i cases hi | cons x xs ih => simp only [Expression.rejectValue] at hi split_ifs at hi with hx · cases hi; exact hx · exact ih hi def bankEval {A : Type*} : DrawTree A → Bank → Option A × Bank | .leaf a,bank => (some a,bank) | .draw _ _,[] => (none,[]) | .draw v k,rows::bank => match hi : Expression.rejectValue (v+1) (Nat.clog 2 (v+1)) rows with | none => (none,bank) | some i => bankEval (k ⟨i,rejectValue_lt _ _ _ hi⟩) bank lemma bankEval_bind {A B : Type*} (t : DrawTree A) (f : A → DrawTree B) (bank : Bank) : bankEval (t.bind f) bank= match bankEval t bank with | (none,rest) => (none,rest) | (some a,rest) => bankEval (f a) rest := by induction t generalizing bank with | leaf a => rfl | draw v k ih => cases bank with | nil => rfl | cons rows bank => simp only [DrawTree.bind,bankEval] split <;> first | rfl | exact ih _ bank lemma bankEval_map {A B : Type*} (t : DrawTree A) (f : A → B) (bank : Bank) : bankEval (t.map f) bank=((bankEval t bank).1.map f,(bankEval t bank).2) := by rw [DrawTree.map,bankEval_bind] cases bankEval t bank with | mk o rest => cases o <;> rfl def bankEncode {H D M : ℕ} (bits : Fin M → Fin D → BitWord H) : Bank := List.ofFn (fun m => List.ofFn (fun d => List.ofFn (bits m d))) lemma bankEncode_succ {H D M : ℕ} (bits : Fin (M+1) → Fin D → BitWord H) : bankEncode bits=List.ofFn (fun d => List.ofFn (bits 0 d))::bankEncode (Fin.tail bits) := by exact List.ofFn_succ lemma bankEval_run {A : Type*} (H D M : ℕ) (t : DrawTree A) (ht : DrawTree.Fits H M t) (bits : Fin M → Fin D → BitWord H) : (bankEval t (bankEncode bits)).1=DrawTree.run H D M t bits := by induction t generalizing M with | leaf a => cases M <;> rfl | draw v k ih => cases M with | zero => exact False.elim ht | succ M => rw [bankEncode_succ] simp only [bankEval,DrawTree.run,dite_eq_left ht.1] have he := rejectValue_prefix (v+1) (Nat.clog 2 (v+1)) H D ht.1 (bits 0) cases hu : boundedUniform (v+1) (Nat.clog 2 (v+1)) D (fun i => bitPrefix _ H ht.1 (bits 0 i)) with | none => simp only [hu,Option.map_none] at he split · rfl · rename_i i hi have hh := he.symm.trans hi cases hh | some i => simp only [hu,Option.map_some] at he split · rename_i hi have hh := he.symm.trans hi cases hh · rename_i j hj have hh := Option.some.inj (he.symm.trans hj) subst j exact ih i M (ht.2 i) (Fin.tail bits) open Expression def zeroValue : (a : DataType) → Value a | .unit => () | .bool => false | .nat => 0 | .word => [] | .prod a b => (zeroValue a,zeroValue b) | .list _ => [] def optionalValue (a : DataType) : Option (Value a) → Value (Optional a) := optionData (zeroValue a) def decodeOptional {a : DataType} (x : Value (Optional a)) : Option (Value a) := if x.1 then some x.2 else none @[simp] lemma decode_optionalValue (a : DataType) (x : Option (Value a)) : decodeOptional (optionalValue a x)=x := by cases x <;> rfl abbrev Effect (a b : DataType) := Expression (.prod a BankData) (.prod (Optional b) BankData) namespace Expression lemma clog_two_size_pred (v : ℕ) : Nat.clog 2 v=(v-1).size := by apply Nat.le_antisymm · apply (Nat.clog_le_iff_le_pow (by norm_num)).mpr have h := Nat.lt_size_self (v-1) omega · apply Nat.size_le.mpr have h := Nat.le_pow_clog (by norm_num : 1<2) v have hp : 0<2^(Nat.clog 2 v) := by positivity omega def clogCode : Expression .nat .nat := both ident (constant 1) >>> natSub >>> toBits >>> wordLength lemma run_clogCode {n : ℕ} (O : IndependenceOracle n) (v : ℕ) : run O clogCode v=some (Nat.clog 2 v) := by simp only [clogCode,run_compose,run_both,run_ident,run_constant,Option.bind_some,Option.map_some] rw [run_natSub] change run O wordLength (v-1).bits=_ rw [run_wordLength,Nat.size_eq_bits_len,clog_two_size_pred] end Expression open Expression namespace Effect def pure {a b} (p : Expression a b) : Effect a b := both (both (constant true) (fst >>> p)) snd def fail {a b} : Effect a b := both (constant (optionalValue b none)) snd def bind {a b c} (p : Effect a b) (q : Effect b c) : Effect a c := p >>> applyIf (fst >>> fst) (both (constant (optionalValue c none)) snd) (both (fst >>> snd) snd >>> q) def keep {a b} (p : Effect a b) : Effect a (.prod a b) := letIn p (both (applyIf (snd >>> fst >>> fst) (constant (optionalValue (.prod a b) none)) (both (constant true) (both (fst >>> fst) (snd >>> fst >>> snd)))) (snd >>> snd)) def letIn {a b c} (p : Effect a b) (q : Effect (.prod a b) c) : Effect a c := bind (keep p) q def draw : Effect .nat .nat := both (both (snd >>> both ident (constant []) >>> headD) (both fst (fst >>> clogCode)) >>> rejectCode) (snd >>> both ident (constant 1) >>> dropCode) lemma run_pure {n : ℕ} (O : IndependenceOracle n) {a b} (p : Expression a b) (x : Value a) (y : Value b) (bank : Bank) (hp : run O p x=some y) : run O (pure p) (x,bank)=some (optionalValue b (some y),bank) := by simp only [pure,run_both,run_compose,run_fst,run_snd,run_constant, Option.bind_some,hp,Option.map_some] rfl lemma run_fail {n : ℕ} (O : IndependenceOracle n) {a b} (x : Value a) (bank : Bank) : run O (fail (a:=a) (b:=b)) (x,bank)=some (optionalValue b none,bank) := rfl lemma run_bind {n : ℕ} (O : IndependenceOracle n) {a b c} (p : Effect a b) (q : Effect b c) (x : Value a) (bank rest : Bank) (y : Option (Value b)) (hp : run O p (x,bank)=some (optionalValue b y,rest)) : run O (bind p q) (x,bank)= match y with | none => some (optionalValue c none,rest) | some z => run O q (z,rest) := by cases y <;> dsimp only <;> rw [bind,run_compose,hp,Option.bind_some,run_applyIf] <;> rfl lemma run_keep {n : ℕ} (O : IndependenceOracle n) {a b} (p : Effect a b) (x : Value a) (bank rest : Bank) (y : Value b) (hp : run O p (x,bank)=some (optionalValue b (some y),rest)) : run O (keep p) (x,bank)=some (optionalValue (.prod a b) (some (x,y)),rest) := by rw [keep,run_letIn,hp] rfl lemma run_draw {n : ℕ} (O : IndependenceOracle n) (v : ℕ) (bank : Bank) : run O draw (v,bank)=some (optionData 0 (Expression.rejectValue v (Nat.clog 2 v) (bank.headD [])),bank.drop 1) := by simp only [draw,run_both,run_compose,run_fst,run_snd,run_ident,run_constant,Option.bind_some,Option.map_some] rw [run_headD,run_clogCode,run_dropCode] simp only [Option.bind_some,Option.map_some] rw [run_rejectCode] rfl def Realizes {n : ℕ} (O : IndependenceOracle n) {A : Type*} {a b : DataType} (p : Effect a b) (encode : A → Value b) (x : Value a) (t : DrawTree A) : Prop := ∀ bank, run O p (x,bank)=some (optionalValue b ((bankEval t bank).1.map encode),(bankEval t bank).2) lemma realizes_pure {n : ℕ} (O : IndependenceOracle n) {A : Type*} {a b : DataType} (p : Expression a b) (encode : A → Value b) (x : Value a) (y : A) (hp : run O p x=some (encode y)) : Realizes O (pure p) encode x (.leaf y) := by intro bank exact run_pure O p x (encode y) bank hp lemma realizes_bind {n : ℕ} (O : IndependenceOracle n) {A B : Type*} {a b c : DataType} (p : Effect a b) (q : Effect b c) (ea : A → Value b) (eb : B → Value c) (x : Value a) (t : DrawTree A) (f : A → DrawTree B) (hp : Realizes O p ea x t) (hq : ∀ y,Realizes O q eb (ea y) (f y)) : Realizes O (bind p q) eb x (t.bind f) := by intro bank rw [bankEval_bind] cases ht : bankEval t bank with | mk out rest => have hh := hp bank rw [ht] at hh cases out with | none => exact run_bind O p q x bank rest none hh | some y => rw [run_bind O p q x bank rest (some (ea y)) hh] exact hq y rest lemma realizes_keep {n : ℕ} (O : IndependenceOracle n) {A : Type*} {a b : DataType} (p : Effect a b) (ea : A → Value b) (x : Value a) (t : DrawTree A) (hp : Realizes O p ea x t) : Realizes O (keep p) (fun y => (x,ea y)) x t := by intro bank have hh := hp bank cases ht : bankEval t bank with | mk out rest => rw [ht] at hh cases out with | none => rw [keep,run_letIn,hh]; rfl | some y => exact run_keep O p x bank rest (ea y) hh lemma realizes_letIn {n : ℕ} (O : IndependenceOracle n) {A B : Type*} {a b c : DataType} (p : Effect a b) (q : Effect (.prod a b) c) (ea : A → Value b) (eb : B → Value c) (x : Value a) (t : DrawTree A) (f : A → DrawTree B) (hp : Realizes O p ea x t) (hq : ∀ y,Realizes O q eb (x,ea y) (f y)) : Realizes O (letIn p q) eb x (t.bind f) := realizes_bind O (keep p) q _ eb x t f (realizes_keep O p ea x t hp) hq lemma realizes_draw {n : ℕ} (O : IndependenceOracle n) (v : ℕ) : Realizes O draw Fin.val (v+1) (.draw v DrawTree.leaf) := by intro bank rw [run_draw] cases bank with | nil => rfl | cons rows bank => simp only [bankEval] split · rename_i hi simp only [List.headD_cons,List.drop_succ_cons,List.drop_zero,hi,Option.map_none] rfl · rename_i i hi simp only [List.headD_cons,List.drop_succ_cons,List.drop_zero,hi,Option.map_some] rfl def map {a b c} (p : Effect a b) (q : Expression b c) : Effect a c := bind p (pure q) def precompose {a b c} (p : Expression a b) (q : Effect b c) : Effect a c := onLeft p >>> q def choose {a b} (test : Expression a .bool) (p q : Effect a b) : Effect a b := applyIf (fst >>> test) p q lemma run_precompose {n : ℕ} (O : IndependenceOracle n) {a b c} (p : Expression a b) (q : Effect b c) (x : Value a) (y : Value b) (bank : Bank) (hp : run O p x=some y) : run O (precompose p q) (x,bank)=run O q (y,bank) := by simp only [precompose,onLeft,run_compose,run_both,run_fst,run_snd,Option.bind_some,hp,Option.map_some] lemma realizes_precompose {n : ℕ} (O : IndependenceOracle n) {A : Type*} {a b c} (p : Expression a b) (q : Effect b c) (ea : A → Value c) (x : Value a) (y : Value b) (t : DrawTree A) (hp : run O p x=some y) (hq : Realizes O q ea y t) : Realizes O (precompose p q) ea x t := by intro bank rw [run_precompose O p q x y bank hp] exact hq bank lemma run_choose {n : ℕ} (O : IndependenceOracle n) {a b} (test : Expression a .bool) (p q : Effect a b) (x : Value a) (bank : Bank) (v : Bool) (ht : run O test x=some v) : run O (choose test p q) (x,bank)=if v then run O q (x,bank) else run O p (x,bank) := by rw [choose,run_applyIf] change ((run O test x).bind fun v => if v then _ else _)=_ rw [ht,Option.bind_some] lemma realizes_map {n : ℕ} (O : IndependenceOracle n) {A B : Type*} {a b c} (p : Effect a b) (q : Expression b c) (ea : A → Value b) (eb : B → Value c) (x : Value a) (t : DrawTree A) (f : A → B) (hp : Realizes O p ea x t) (hq : ∀ y,run O q (ea y)=some (eb (f y))) : Realizes O (map p q) eb x (t.map f) := realizes_bind O p (pure q) ea eb x t (fun y => .leaf (f y)) hp (fun y => realizes_pure O q eb (ea y) (f y) (hq y)) end Effect def iterateM {A : Type*} (f : A → Option A) : ℕ → A → Option A | 0,x => some x | k+1,x => (f x).bind (iterateM f k) lemma iterateM_some {A : Type*} (f : A → Option A) (x : A) (h : f x=some x) (k : ℕ) : iterateM f k x=some x := by induction k with | zero => rfl | succ k ih => rw [iterateM,h,Option.bind_some,ih] namespace Expression lemma run_iterateNatM {n : ℕ} (O : IndependenceOracle n) {a : DataType} (p : Expression a a) (k : ℕ) (x : Value a) : run O (iterateNat p) (k,x)=iterateM (run O p) k x := by have hf : ∀ (w : Word) (z : Value a), foldValue (run O (snd (a:=.bool) >>> p)) w z=iterateM (run O p) w.length z := by intro w induction w with | nil => intro z; rfl | cons b w ih => intro z change ((run O p z).bind (foldValue (run O (snd (a:=.bool) >>> p)) w))=_ simp only [List.length_cons,iterateM] congr 1 funext v exact ih v obtain ⟨w,hw,hlen⟩ := run_unary O k simp only [iterateNat,onLeft,run_compose,run_both,run_fst,run_snd,Option.bind_some,Option.map_some] rw [hw] change foldValue (run O (snd (a:=.bool) >>> p)) w x=_ rw [hf,hlen] end Expression namespace Effect def loopStep {a} (p : Effect a a) : Expression (.prod (Optional a) BankData) (.prod (Optional a) BankData) := applyIf (fst >>> fst) ident (both (fst >>> snd) snd >>> p) def repeatCode {a} (p : Effect a a) : Effect (.prod .nat a) a := both (fst >>> fst) (both (both (constant (b:=.bool) true) (fst >>> snd)) snd) >>> iterateNat (loopStep p) lemma run_loopStep_none {n : ℕ} (O : IndependenceOracle n) {a} (p : Effect a a) (bank : Bank) : run O (loopStep p) (optionalValue a none,bank)=some (optionalValue a none,bank) := rfl lemma run_loopStep_some {n : ℕ} (O : IndependenceOracle n) {a} (p : Effect a a) (x : Value a) (bank : Bank) : run O (loopStep p) (optionalValue a (some x),bank)=run O p (x,bank) := rfl lemma run_repeat {n : ℕ} (O : IndependenceOracle n) {a} (p : Effect a a) (k : ℕ) (x : Value a) (bank : Bank) : run O (repeatCode p) ((k,x),bank)=iterateM (run O (loopStep p)) k (optionalValue a (some x),bank) := by change run O (iterateNat (loopStep p)) (k,(optionalValue a (some x),bank))=_ exact run_iterateNatM O _ _ _ def treeRepeat {A : Type*} (f : A → DrawTree A) : ℕ → A → DrawTree A | 0,x => .leaf x | k+1,x => (f x).bind (treeRepeat f k) lemma realizes_repeat {n : ℕ} (O : IndependenceOracle n) {A : Type*} {a} (p : Effect a a) (ea : A → Value a) (f : A → DrawTree A) (hp : ∀ x,Realizes O p ea (ea x) (f x)) (k : ℕ) (x : A) : Realizes O (repeatCode p) ea (k,ea x) (treeRepeat f k x) := by intro bank rw [run_repeat] induction k generalizing x bank with | zero => rfl | succ k ih => rw [iterateM,run_loopStep_some,hp x bank,Option.bind_some,treeRepeat,bankEval_bind] cases ht : bankEval (f x) bank with | mk out rest => cases out with | none => simpa only [Option.map_none] using iterateM_some (run O (loopStep p)) (optionalValue a none,rest) (run_loopStep_none O p rest) k | some y => exact ih y rest end Effect end MachineCode namespace DrawTree variable {A B : Type*} lemma Reindexed.trans {t u v : DrawTree A} (h : Reindexed t u) (g : Reindexed u v) : Reindexed t v := by induction h generalizing v with | leaf a => cases g; exact .leaf a | draw m k l e h ih => cases g with | draw _ _ z f gz => exact .draw m k z (e.trans f) (fun i => ih i (gz (e i))) lemma uniformVia_reindexed_via (A : Type*) [Fintype A] [Nonempty A] (e f : Fin (Fintype.card A) ≃ A) : Reindexed (uniformVia A e) (uniformVia A f) := (uniformVia_reindexed A e).trans (uniformVia_reindexed A f).symm end DrawTree namespace MachineCode open Expression namespace Effect def RealizesLaw {n : ℕ} (O : IndependenceOracle n) {A : Type*} {a b : DataType} (p : Effect a b) (encode : A → Value b) (x : Value a) (t : DrawTree A) : Prop := ∃ u, DrawTree.Reindexed t u ∧ Realizes O p encode x u lemma Realizes.law {n : ℕ} {O : IndependenceOracle n} {A : Type*} {a b} {p : Effect a b} {e : A → Value b} {x : Value a} {t : DrawTree A} (h : Realizes O p e x t) : RealizesLaw O p e x t := ⟨t,.refl t,h⟩ lemma RealizesLaw.reindex {n : ℕ} {O : IndependenceOracle n} {A : Type*} {a b} {p : Effect a b} {e : A → Value b} {x : Value a} {t u : DrawTree A} (h : RealizesLaw O p e x u) (ht : DrawTree.Reindexed t u) : RealizesLaw O p e x t := by rcases h with ⟨v,hv,hp⟩ exact ⟨v,ht.trans hv,hp⟩ lemma law_bind {n : ℕ} (O : IndependenceOracle n) {A B : Type*} {a b c} (p : Effect a b) (q : Effect b c) (ea : A → Value b) (eb : B → Value c) (x : Value a) (t : DrawTree A) (f : A → DrawTree B) (hp : RealizesLaw O p ea x t) (hq : ∀ y,RealizesLaw O q eb (ea y) (f y)) : RealizesLaw O (bind p q) eb x (t.bind f) := by classical rcases hp with ⟨u,hu,hp⟩ choose g hg hq using hq exact ⟨u.bind g,hu.bind hg,realizes_bind O p q ea eb x u g hp hq⟩ lemma law_letIn {n : ℕ} (O : IndependenceOracle n) {A B : Type*} {a b c} (p : Effect a b) (q : Effect (.prod a b) c) (ea : A → Value b) (eb : B → Value c) (x : Value a) (t : DrawTree A) (f : A → DrawTree B) (hp : RealizesLaw O p ea x t) (hq : ∀ y,RealizesLaw O q eb (x,ea y) (f y)) : RealizesLaw O (letIn p q) eb x (t.bind f) := by classical rcases hp with ⟨u,hu,hp⟩ choose g hg hq using hq exact ⟨u.bind g,hu.bind hg,realizes_letIn O p q ea eb x u g hp hq⟩ lemma law_precompose {n : ℕ} (O : IndependenceOracle n) {A : Type*} {a b c} (p : Expression a b) (q : Effect b c) (ea : A → Value c) (x : Value a) (y : Value b) (t : DrawTree A) (hp : run O p x=some y) (hq : RealizesLaw O q ea y t) : RealizesLaw O (precompose p q) ea x t := by rcases hq with ⟨u,hu,hq⟩ exact ⟨u,hu,realizes_precompose O p q ea x y u hp hq⟩ lemma law_map {n : ℕ} (O : IndependenceOracle n) {A B : Type*} {a b c} (p : Effect a b) (q : Expression b c) (ea : A → Value b) (eb : B → Value c) (x : Value a) (t : DrawTree A) (f : A → B) (hp : RealizesLaw O p ea x t) (hq : ∀ y,run O q (ea y)=some (eb (f y))) : RealizesLaw O (map p q) eb x (t.map f) := by rcases hp with ⟨u,hu,hp⟩ exact ⟨u.map f,hu.map f,realizes_map O p q ea eb x u f hp hq⟩ lemma law_choose {n : ℕ} (O : IndependenceOracle n) {A : Type*} {a b} (test : Expression a .bool) (p q : Effect a b) (ea : A → Value b) (x : Value a) (t : DrawTree A) (v : Bool) (ht : run O test x=some v) (h : RealizesLaw O (if v then q else p) ea x t) : RealizesLaw O (choose test p q) ea x t := by rcases h with ⟨u,hu,hp⟩ refine ⟨u,hu,fun bank => ?_⟩ rw [run_choose O test p q x bank v ht] cases v <;> exact hp bank end Effect end MachineCode namespace DrawTree variable {A B C : Type*} lemma bind_leaf (t : DrawTree A) : t.bind leaf=t := by induction t with | leaf a => rfl | draw v f ih => simp only [bind,ih] lemma map_bind (t : DrawTree A) (f : A → B) (g : B → DrawTree C) : (t.map f).bind g=t.bind (fun a => g (f a)) := by rw [DrawTree.map,bind_assoc] rfl lemma bind_map (t : DrawTree A) (f : A → DrawTree B) (g : B → C) : (t.bind f).map g=t.bind (fun a => (f a).map g) := bind_assoc t f _ lemma map_map (t : DrawTree A) (f : A → B) (g : B → C) : (t.map f).map g=t.map (g ∘ f) := map_bind t f _ end DrawTree namespace MachineCode open Expression def optionEncode {A : Type*} {a} (e : A → Value a) (x : Option A) : Value (Optional a) := optionalValue a (x.map e) @[simp] lemma optionEncode_none {A : Type*} {a} (e : A → Value a) : optionEncode e none=(false,zeroValue a) := rfl @[simp] lemma optionEncode_some {A : Type*} {a} (e : A → Value a) (x : A) : optionEncode e (some x)=(true,e x) := rfl namespace Effect def someCode {a b} (p : Effect a b) : Effect a (Optional b) := map p (both (constant true) ident) def noneCode {a b} : Effect a (Optional b) := pure (constant (optionalValue b none)) def optionContinue {a b} (q : Effect a (Optional b)) : Effect (Optional a) (Optional b) := choose fst noneCode (precompose snd q) def optionBind {a b c} (p : Effect a (Optional b)) (q : Effect b (Optional c)) : Effect a (Optional c) := bind p (optionContinue q) lemma law_some {n : ℕ} (O : IndependenceOracle n) {A : Type*} {a b} (p : Effect a b) (ea : A → Value b) (x : Value a) (t : DrawTree A) (h : RealizesLaw O p ea x t) : RealizesLaw O (someCode p) (optionEncode ea) x (t.map some) := law_map O p _ ea (optionEncode ea) x t some h (fun _ => rfl) lemma law_none {n : ℕ} (O : IndependenceOracle n) {A : Type*} {a b} (ea : A → Value b) (x : Value a) : RealizesLaw O (noneCode (a:=a) (b:=b)) (optionEncode ea) x (.leaf none) := (realizes_pure O _ _ _ none rfl).law lemma law_optionContinue {n : ℕ} (O : IndependenceOracle n) {A B : Type*} {a b} (q : Effect a (Optional b)) (ea : A → Value a) (eb : B → Value b) (f : A → DrawTree (Option B)) (x : Option A) (hq : ∀ y,RealizesLaw O q (optionEncode eb) (ea y) (f y)) : RealizesLaw O (optionContinue q) (optionEncode eb) (optionEncode ea x) (match x with | none => .leaf none | some y => f y) := by unfold optionContinue cases x with | none => exact law_choose O _ _ _ _ _ _ false rfl (law_none O eb _) | some y => exact law_choose O _ _ _ _ _ _ true rfl (law_precompose O snd q _ _ _ _ rfl (hq y)) lemma law_optionBind {n : ℕ} (O : IndependenceOracle n) {A B : Type*} {a b c} (p : Effect a (Optional b)) (q : Effect b (Optional c)) (ea : A → Value b) (eb : B → Value c) (x : Value a) (t : DrawTree (Option A)) (f : A → DrawTree (Option B)) (hp : RealizesLaw O p (optionEncode ea) x t) (hq : ∀ y,RealizesLaw O q (optionEncode eb) (ea y) (f y)) : RealizesLaw O (optionBind p q) (optionEncode eb) x (t.optionBind f) := law_bind O p (optionContinue q) (optionEncode ea) (optionEncode eb) x t _ hp (fun y => law_optionContinue O q ea eb f y hq) lemma law_repeat {n : ℕ} (O : IndependenceOracle n) {A : Type*} {a} (p : Effect a a) (ea : A → Value a) (f : A → DrawTree A) (hp : ∀ x,RealizesLaw O p ea (ea x) (f x)) (k : ℕ) (x : A) : RealizesLaw O (repeatCode p) ea (k,ea x) (treeRepeat f k x) := by classical choose g hg hp using hp have hh : ∀ k x, DrawTree.Reindexed (treeRepeat f k x) (treeRepeat g k x) := by intro k induction k with | zero => intro x; exact .leaf x | succ k ih => intro x; exact (hg x).bind ih exact ⟨treeRepeat g k x,hh k x,realizes_repeat O p ea g hp k x⟩ lemma treeRepeat_succ_last {A : Type*} (f : A → DrawTree A) (k : ℕ) (x : A) : treeRepeat f (k+1) x=(treeRepeat f k x).bind f := by induction k generalizing x with | zero => exact DrawTree.bind_leaf (f x) | succ k ih => change (f x).bind (treeRepeat f (k+1))=((f x).bind (treeRepeat f k)).bind f rw [DrawTree.bind_assoc] congr 1 funext y exact ih y lemma treeRepeat_option {A : Type*} (f : A → DrawTree (Option A)) (k : ℕ) (x : A) : treeRepeat (fun u => match u with | none => .leaf none | some a => f a) k (some x)= DrawTree.iterate f k x := by induction k with | zero => rfl | succ k ih => rw [treeRepeat_succ_last,ih]; rfl def iterateCode {a} (p : Effect a (Optional a)) : Effect (.prod .nat a) (Optional a) := precompose (both fst (both (constant true) snd)) (repeatCode (optionContinue p)) lemma law_iterate {n : ℕ} (O : IndependenceOracle n) {A : Type*} {a} (p : Effect a (Optional a)) (ea : A → Value a) (f : A → DrawTree (Option A)) (hp : ∀ x,RealizesLaw O p (optionEncode ea) (ea x) (f x)) (k : ℕ) (x : A) : RealizesLaw O (iterateCode p) (optionEncode ea) (k,ea x) (DrawTree.iterate f k x) := by unfold iterateCode apply law_precompose O _ _ _ _ (k,optionEncode ea (some x)) _ rfl rw [←treeRepeat_option] apply law_repeat intro u exact law_optionContinue O p ea ea f u hp end Effect lemma polySafe_reparam {a b : DataType} (p : Expression a b) (R : ℕ → Value a → Prop) (hp : PolySafe p R) (g : SizePolynomial) : PolySafe p (fun S x => R (g.eval S) x) := by obtain ⟨f,hf⟩ := hp exact ⟨f.subst g,fun O S x hx => by rw [SizePolynomial.eval_subst]; exact hf O _ x hx⟩ lemma polySafe_post {a b c : DataType} (p : Expression a b) (q : Expression b c) (R : ℕ → Value a → Prop) (hp : PolySafe p R) (hq : Controlled q) : PolySafe (p >>> q) R := by obtain ⟨f,hf⟩ := hp apply polySafe_compose p q R (fun S y => width y≤f.eval S) ⟨f,hf⟩ (polySafe_of_controlled q hq _ f (by intros; assumption)) intro n O S x hx y hy exact safe_output (hf O S x hx) hy lemma foldValue_iterateM {n : ℕ} (O : IndependenceOracle n) {a : DataType} (p : Expression a a) (xs : List Bool) (z : Value a) : foldValue (run O (Expression.snd (a:=.bool) >>> p)) xs z=iterateM (run O p) xs.length z := by induction xs generalizing z with | nil => rfl | cons b xs ih => simp only [foldValue,run_compose,run_snd,Option.bind_some,List.length_cons,iterateM]; simp_rw [ih] lemma polySafe_iterateNat {a : DataType} (p : Expression a a) (R : ℕ → Value (.prod .nat a) → Prop) (Q : ℕ → Value a → Prop) (hp : PolySafe p Q) (g : SizePolynomial) (hinput : ∀ S k z,R S (k,z) → k+width (a:=a) z≤g.eval S) (hacc : ∀ {n : ℕ} (O : IndependenceOracle n) S k z,R S (k,z) → ∀ j,j≤k → ∀ y,iterateM (run O p) j z=some y → width (a:=a) y≤g.eval S) (hbody : ∀ {n : ℕ} (O : IndependenceOracle n) S k z,R S (k,z) → ∀ j,j k≤g.eval S) (polySafe_of_controlled Expression.fst (by control) R T hnatwidth) (polySafe_reparam unary (fun S k => k≤S) polySafe_unary g) intro n O S x hx y hy obtain ⟨k,z⟩ := x simp only [run_fst, Option.some.injEq] at hy subst y have hh : k+width (a:=a) z≤g.eval S := hinput S k z hx exact (Nat.le_add_right k (width (a:=a) z)).trans hh · exact polySafe_of_controlled Expression.snd (by control) R T hnatwidth let Rw : ℕ → Value (.prod .word a) → Prop := fun S x => R S (x.1.length,x.2) let Rl : ℕ → Value (.prod (.list .bool) a) → Prop := fun S x => R S (x.1.length,x.2) have hw : ∀ S x,Rw S x → width x≤T.eval S := by intro S x hx obtain ⟨w,z⟩ := x have hh : w.length+width (a:=a) z≤g.eval S := hinput S w.length z hx rw [width_pair (a:=.word) (b:=a),width_word] dsimp [T,SizePolynomial.eval] omega have hfold : PolySafe (.fold (snd >>> p)) Rl := by refine polySafe_fold (Expression.snd (a:=.bool) >>> p) Rl (fun S x => width x≤T.eval S ∧ Q S x.2) ?_ T ?_ ?_ ?_ · apply polySafe_compose _ _ _ Q (polySafe_of_controlled Expression.snd (by control) _ T (by intro S x hx; exact hx.1)) hp intro n O S x hx y hy cases hy exact hx.2 · intro S x hx obtain ⟨xs,z⟩ := x have hh : xs.length+width (a:=a) z≤g.eval S := hinput S xs.length z hx rw [width_pair (a:=.list .bool) (b:=a),width_list_bool] dsimp [T,SizePolynomial.eval] omega · intro n O S xs z hx pre post he y hy rw [foldValue_iterateM] at hy have hj : pre.length≤xs.length := by rw [he,List.length_append]; omega have hh := hacc O S xs.length z hx pre.length hj y hy dsimp [T,SizePolynomial.eval] omega · intro n O S xs z hx pre b post he y hy rw [foldValue_iterateM] at hy have hj : pre.length rfl | succ k ih => rw [iterateM,hp,Option.bind_some,ih,Function.iterate_succ_apply] lemma width_list_le {a : DataType} (xs : List (Value a)) (S : ℕ) (hs : ∀ x∈xs,width (a:=a) x≤S) : width (a:=.list a) xs≤xs.length*(2*S+2) := by induction xs with | nil => simp | cons x xs ih => have hx := hs x (by simp) have hh := ih (fun y hy => hs y (by simp [hy])) rw [width_cons (a:=a),List.length_cons,Nat.add_mul,Nat.one_mul] omega lemma width_range (k : ℕ) : width (a:=.list .nat) (List.range k)≤k*(2*k+2) := by simpa only [List.length_range] using width_list_le (a:=.nat) (List.range k) k (by intro x hx exact (bits_length_le_value x).trans (List.mem_range.mp hx).le) lemma width_rangeState (k : ℕ) : width (a:=.prod .nat (.list .nat)) (k,(List.range k).reverse)≤4*(k+1)^2 := by rw [width_pair (a:=.nat) (b:=.list .nat),width_nat,width_list_reverse (a:=.nat)] have h := width_range k have h' := bits_length_le_value k nlinarith lemma controlled_rangeStep : Controlled rangeStepCode := by unfold rangeStepCode; control lemma polySafe_rangeCode : PolySafe rangeCode (fun S k => k≤S) := by let g : SizePolynomial := .mul (.constant 10) (.mul (.add .input (.constant 1)) (.add .input (.constant 1))) have hg (S : ℕ) : g.eval S=10*(S+1)^2 := by simp [g,SizePolynomial.eval,pow_two] let R : ℕ → Value (.prod .nat (.prod .nat (.list .nat))) → Prop := fun S x => x.1≤S ∧ x.2=(0,[]) have hi : PolySafe (iterateNat rangeStepCode) R := by refine polySafe_iterateNat rangeStepCode R (fun S z => width z≤g.eval S) (polySafe_of_controlled _ controlled_rangeStep _ g (by intros; assumption)) g ?_ ?_ ?_ · intro S k z hx dsimp [R] at hx rcases hx with ⟨hk,rfl⟩ rw [hg] change k+1≤10*(S+1)^2 exact (Nat.add_le_add_right hk 1).trans (by nlinarith) · intro n O S k z hx j hj y hy dsimp [R] at hx rcases hx with ⟨hk,rfl⟩ rw [iterateM_total (run O rangeStepCode) rangeStep (fun _ => rfl),rangeStep_iterate] at hy cases hy apply (width_rangeState j).trans rw [hg] have hjk : Nat.le j S := hj.trans hk exact (Nat.mul_le_mul_left 4 (Nat.pow_le_pow_left (Nat.add_le_add_right hjk 1) 2)).trans (Nat.mul_le_mul_right _ (by decide : 4≤10)) · intro n O S k z hx j hj y hy dsimp [R] at hx rcases hx with ⟨hk,rfl⟩ rw [iterateM_total (run O rangeStepCode) rangeStep (fun _ => rfl),rangeStep_iterate] at hy cases hy apply (width_rangeState j).trans rw [hg] have hjk : Nat.le j S := hj.le.trans hk exact (Nat.mul_le_mul_left 4 (Nat.pow_le_pow_left (Nat.add_le_add_right hjk 1) 2)).trans (Nat.mul_le_mul_right _ (by decide : 4≤10)) unfold rangeCode apply polySafe_compose _ _ _ R (polySafe_of_controlled _ (by control) _ .input (by intro S k hk exact (bits_length_le_value k).trans hk)) (polySafe_post _ _ R hi (controlled_compose _ _ (by control) controlled_listReverse)) intro n O S x hx y hy cases hy exact ⟨hx,rfl⟩ lemma controlled_wordRange : Controlled (wordLength >>> rangeCode) := by apply polySafe_controlled apply polySafe_compose _ _ _ (fun S k => k≤S) (polySafe_of_controlled _ controlled_wordLength _ .input (by intros; assumption)) polySafe_rangeCode intro n O S x hx y hy rw [run_wordLength] at hy cases hy exact hx lemma run_filterStep_partial {n : ℕ} (O : IndependenceOracle n) {a b : DataType} (p : Expression (.prod a b) .bool) (x : Value a) (ys : List (Value a)) (z : Value b) : run O (filterStep p) (x,(ys,z))=(run O p (x,z)).map (fun t => ((if t then x::ys else ys),z)) := by simp only [filterStep,run_both,run_applyIf,run_compose,run_fst,run_snd,Option.bind_some,Option.map_some] cases he : run O p (x,z) with | none => rfl | some t => cases t <;> rfl lemma fold_filterStep_bound {n : ℕ} (O : IndependenceOracle n) {a b : DataType} (p : Expression (.prod a b) .bool) (xs ys : List (Value a)) (z : Value b) (v : Value (.prod (.list a) b)) (hv : foldValue (run O (filterStep p)) xs (ys,z)=some v) : width (a:=.list a) v.1≤width (a:=.list a) xs+width (a:=.list a) ys ∧ v.2=z := by induction xs generalizing ys with | nil => cases hv; simp | cons x xs ih => rw [foldValue,run_filterStep_partial] at hv cases he : run O p (x,z) with | none => simp [he] at hv | some t => simp only [he,Option.map_some,Option.bind_some] at hv cases t with | false => have hh := ih ys hv rw [width_cons (a:=a)] exact ⟨by omega,hh.2⟩ | true => have hh := ih (x::ys) hv rw [width_cons (a:=a)] at hh ⊢ exact ⟨by omega,hh.2⟩ lemma controlled_filterStep {a b : DataType} (p : Expression (.prod a b) .bool) (hp : Controlled p) : Controlled (filterStep p) := by unfold filterStep; control lemma controlled_filterFold {a b : DataType} (p : Expression (.prod a b) .bool) (hp : Controlled p) : Controlled (.fold (filterStep p)) := by apply controlled_fold _ (controlled_filterStep p hp) (.mul (.constant 3) .input) intro n O xs z pre post he y hy obtain ⟨ys,ctx⟩ := z have hh := fold_filterStep_bound O p pre ys ctx y hy have hpre : width (a:=.list a) pre≤width (a:=.list a) xs := by rw [he,width_list_append]; omega obtain ⟨out,outctx⟩ := y dsimp only [Prod.fst,Prod.snd] at hh rw [width_pair (a:=.list a) (b:=b),width_pair (a:=.list a) (b:=.prod (.list a) b), width_pair (a:=.list a) (b:=b),hh.2] dsimp [SizePolynomial.eval] omega lemma controlled_filterWith {a b : DataType} (p : Expression (.prod a b) .bool) (hp : Controlled p) : Controlled (filterWith p) := by unfold filterWith have hf := controlled_filterFold p hp have hr := controlled_listReverse (a:=a) control open scoped Classical noncomputable def stateEncode {n : ℕ} (S : Set (Fin n⊕Fin n)) : Value StateData := (List.ofFn (fun i => decide (Sum.inl i∈S)),List.ofFn (fun i => decide (Sum.inr i∈S))) @[simp] lemma stateEncode_left_length {n : ℕ} (S : Set (Fin n⊕Fin n)) : (stateEncode S).1.length=n := List.length_ofFn @[simp] lemma stateEncode_right_length {n : ℕ} (S : Set (Fin n⊕Fin n)) : (stateEncode S).2.length=n := List.length_ofFn @[simp] lemma stateEncode_repr {n : ℕ} (S : Set (Fin n⊕Fin n)) : representedState n (stateEncode S)=S := by ext i cases i <;> simp [representedState,stateEncode,wordSet] lemma stateEncode_get_left {n : ℕ} (S : Set (Fin n⊕Fin n)) (i : Fin n) : (stateEncode S).1[i.val]?.getD false=decide (Sum.inl i∈S) := by simp [stateEncode] lemma stateEncode_get_right {n : ℕ} (S : Set (Fin n⊕Fin n)) (i : Fin n) : (stateEncode S).2[i.val]?.getD false=decide (Sum.inr i∈S) := by simp [stateEncode] namespace Expression def boolXor : Expression (.prod .bool .bool) .bool := branch ident boolNot lemma run_boolXor {n : ℕ} (O : IndependenceOracle n) (a b : Bool) : run O boolXor (a,b)=some (xor a b) := by cases a <;> cases b <;> rfl def singleAt : Expression (.prod .nat StateData) .bool := both (both (snd >>> fst) fst >>> wordGet) (both (snd >>> snd) fst >>> wordGet) >>> boolXor def fullAt : Expression (.prod .nat StateData) .bool := both (both (snd >>> fst) fst >>> wordGet) (both (snd >>> snd) fst >>> wordGet) >>> boolAnd def emptyAt : Expression (.prod .nat StateData) .bool := both (both (snd >>> fst) fst >>> wordGet) (both (snd >>> snd) fst >>> wordGet) >>> boolOr >>> boolNot def singleValue (i : ℕ) (S : Word×Word) : Bool := xor (S.1[i]?.getD false) (S.2[i]?.getD false) def fullValue (i : ℕ) (S : Word×Word) : Bool := (S.1[i]?.getD false) && (S.2[i]?.getD false) def emptyValue (i : ℕ) (S : Word×Word) : Bool := !(S.1[i]?.getD false || S.2[i]?.getD false) lemma run_singleAt {n : ℕ} (O : IndependenceOracle n) (i : ℕ) (S : Word×Word) : run O singleAt (i,S)=some (singleValue i S) := by simp only [singleAt,run_compose,run_both,run_fst,run_snd,Option.bind_some,Option.map_some] rw [run_wordGet,run_wordGet] exact run_boolXor O _ _ lemma run_fullAt {n : ℕ} (O : IndependenceOracle n) (i : ℕ) (S : Word×Word) : run O fullAt (i,S)=some (fullValue i S) := by simp only [fullAt,run_compose,run_both,run_fst,run_snd,Option.bind_some,Option.map_some] rw [run_wordGet,run_wordGet] exact run_boolAnd O _ _ lemma run_emptyAt {n : ℕ} (O : IndependenceOracle n) (i : ℕ) (S : Word×Word) : run O emptyAt (i,S)=some (emptyValue i S) := by simp only [emptyAt,run_compose,run_both,run_fst,run_snd,Option.bind_some,Option.map_some] rw [run_wordGet,run_wordGet] change ((run O boolOr _).bind (run O boolNot))=_ rw [run_boolOr]; exact run_boolNot O _ def plainValue (S : Word×Word) : Bool := ((List.range S.1.length).map (fun i => singleValue i S)).all id def plainCode : Expression StateData .bool := both (fst >>> wordLength >>> rangeCode) ident >>> mapWith singleAt >>> listAll lemma run_plainCode {n : ℕ} (O : IndependenceOracle n) (S : Word×Word) : run O plainCode S=some (plainValue S) := by simp only [plainCode,run_compose,run_both,run_fst,run_ident,Option.bind_some,Option.map_some] rw [run_wordLength,Option.bind_some,run_rangeCode] change ((run O (mapWith singleAt) (List.range S.1.length,S)).bind (run O listAll))=_ rw [run_mapWith O singleAt singleValue (run_singleAt O)] exact run_listAll O _ end Expression lemma singleValue_source {n : ℕ} (S : Set (Fin n⊕Fin n)) (i : Fin n) : Expression.singleValue i.val (stateEncode S)=decide (PairSingle (slotPair i) S) := by rw [Expression.singleValue,stateEncode_get_left,stateEncode_get_right] unfold PairSingle slotPair by_cases ha : Sum.inl i∈S <;> by_cases hb : Sum.inr i∈S <;> simp [ha,hb] lemma fullValue_source {n : ℕ} (S : Set (Fin n⊕Fin n)) (i : Fin n) : Expression.fullValue i.val (stateEncode S)=decide (PairFull (slotPair i) S) := by rw [Expression.fullValue,stateEncode_get_left,stateEncode_get_right] unfold PairFull slotPair by_cases ha : Sum.inl i∈S <;> by_cases hb : Sum.inr i∈S <;> simp [ha,hb] lemma emptyValue_source {n : ℕ} (S : Set (Fin n⊕Fin n)) (i : Fin n) : Expression.emptyValue i.val (stateEncode S)=decide (PairEmpty (slotPair i) S) := by rw [Expression.emptyValue,stateEncode_get_left,stateEncode_get_right] unfold PairEmpty slotPair by_cases ha : Sum.inl i∈S <;> by_cases hb : Sum.inr i∈S <;> simp [ha,hb] lemma plainValue_source {n : ℕ} (S : Set (Fin n⊕Fin n)) : Expression.plainValue (stateEncode S)=decide (PlainState (pairedSlots n) S) := by apply Bool.eq_iff_iff.mpr simp only [Expression.plainValue,List.all_map,List.all_eq_true,Function.comp_apply,id_eq, stateEncode_left_length,List.mem_range,decide_eq_true_eq] constructor · intro h p hp obtain ⟨i,hi,rfl⟩ := List.mem_map.mp hp have hh := h i.val i.isLt rw [singleValue_source] at hh exact of_decide_eq_true hh · intro h i hi rw [singleValue_source S ⟨i,hi⟩] exact decide_eq_true (h _ (by simp [pairedSlots])) lemma plainCode_source {n : ℕ} (O : IndependenceOracle n) (S : Set (Fin n⊕Fin n)) : run O Expression.plainCode (stateEncode S)=some (decide (PlainState (pairedSlots n) S)) := by rw [Expression.run_plainCode,plainValue_source] abbrev DefectInput := DataType.prod Expression.NN StateData namespace Expression def defectAt : Expression (.prod .nat DefectInput) .bool := applyIf (both fst (snd >>> fst >>> fst) >>> natEqual) (applyIf (both fst (snd >>> fst >>> snd) >>> natEqual) (both fst (snd >>> snd) >>> singleAt) (both fst (snd >>> snd) >>> fullAt)) (both fst (snd >>> snd) >>> emptyAt) def defectAtValue (i : ℕ) (p : (ℕ×ℕ)×(Word×Word)) : Bool := if i=p.1.1 then emptyValue i p.2 else if i=p.1.2 then fullValue i p.2 else singleValue i p.2 lemma run_defectAt {n : ℕ} (O : IndependenceOracle n) (i p r : ℕ) (S : Word×Word) : run O defectAt (i,((p,r),S))=some (defectAtValue i ((p,r),S)) := by simp only [defectAt,run_applyIf,run_compose,run_both,run_fst,run_snd,Option.bind_some,Option.map_some] rw [run_natEqual] by_cases hi : i=p · subst i; simp only [decide_true,Option.bind_some,ite_true]; simpa only [defectAtValue,ite_true] using run_emptyAt O p S · simp only [hi,decide_false,Option.bind_some,Bool.false_eq_true,ite_false] rw [run_natEqual] by_cases hr : i=r · subst i; simp only [decide_true,Option.bind_some,ite_true] simpa only [defectAtValue,hi,ite_false,ite_true] using run_fullAt O r S · simp only [hr,decide_false,Option.bind_some,Bool.false_eq_true,ite_false] simpa only [defectAtValue,hi,hr,ite_false] using run_singleAt O i S def defectValue (p r : ℕ) (S : Word×Word) : Bool := decide (p≠r) && ((List.range S.1.length).map (fun i => defectAtValue i ((p,r),S))).all id def defectCode : Expression DefectInput .bool := both (fst >>> natEqual >>> boolNot) (both (snd >>> fst >>> wordLength >>> rangeCode) ident >>> mapWith defectAt >>> listAll) >>> boolAnd lemma run_defectCode {n : ℕ} (O : IndependenceOracle n) (p r : ℕ) (S : Word×Word) : run O defectCode ((p,r),S)=some (defectValue p r S) := by simp only [defectCode,run_compose,run_both,run_fst,run_snd,run_ident,Option.bind_some,Option.map_some] rw [run_natEqual,run_wordLength] simp only [Option.bind_some] rw [run_rangeCode] simp only [Option.bind_some,run_boolNot,run_compose] rw [run_mapWith O defectAt defectAtValue (by intro i v; rcases v with ⟨⟨p,r⟩,S⟩; exact run_defectAt O i p r S)] simp only [Option.bind_some,run_listAll,Option.map_some] rw [run_boolAnd] congr 1 simp only [defectValue,decide_not] end Expression lemma slotPair_inj {α : Type*} (i j : α) : slotPair i=slotPair j ↔ i=j := by simp [slotPair] lemma slotPair_mem {n : ℕ} (i : Fin n) : slotPair i∈pairedSlots n := by simp [pairedSlots] lemma defect_paired_iff {n : ℕ} (p r : Fin n) (S : Set (Fin n⊕Fin n)) : DefectState (pairedSlots n) (slotPair p) (slotPair r) S ↔ p≠r ∧ PairEmpty (slotPair p) S ∧ PairFull (slotPair r) S ∧ ∀ i, i≠p → i≠r → PairSingle (slotPair i) S := by constructor · intro h refine ⟨fun hp => h.2.2.1 (congrArg slotPair hp),h.2.2.2.1,h.2.2.2.2.1,?_⟩ intro i hip hir exact h.2.2.2.2.2 (slotPair i) (slotPair_mem i) (fun he => hip ((slotPair_inj i p).mp he)) (fun he => hir ((slotPair_inj i r).mp he)) · rintro ⟨hpr,hp,hr,h⟩ refine ⟨slotPair_mem p,slotPair_mem r,fun he => hpr ((slotPair_inj p r).mp he),hp,hr,?_⟩ intro t ht htp htr obtain ⟨i,hi,rfl⟩ := List.mem_map.mp ht exact h i (fun he => htp (congrArg slotPair he)) (fun he => htr (congrArg slotPair he)) lemma defectValue_source {n : ℕ} (S : Set (Fin n⊕Fin n)) (p r : Fin n) : Expression.defectValue p.val r.val (stateEncode S)= decide (DefectState (pairedSlots n) (slotPair p) (slotPair r) S) := by apply Bool.eq_iff_iff.mpr simp only [Expression.defectValue,Bool.and_eq_true,decide_eq_true_eq,List.all_map,List.all_eq_true, Function.comp_apply,id_eq,stateEncode_left_length,List.mem_range] rw [defect_paired_iff] constructor · rintro ⟨hne,h⟩ have hpr : p≠r := fun he => hne (congrArg Fin.val he) refine ⟨hpr,?_,?_,?_⟩ · have hh := h p.val p.isLt simpa only [Expression.defectAtValue,ite_true,emptyValue_source,decide_eq_true_eq] using hh · have hh := h r.val r.isLt have hrp : r.val≠p.val := Ne.symm hne simpa only [Expression.defectAtValue,hrp,ite_false,ite_true,fullValue_source,decide_eq_true_eq] using hh · intro i hip hir have hh := h i.val i.isLt have hip' : i.val≠p.val := fun he => hip (Fin.ext he) have hir' : i.val≠r.val := fun he => hir (Fin.ext he) simpa only [Expression.defectAtValue,hip',hir',ite_false,singleValue_source,decide_eq_true_eq] using hh · rintro ⟨hpr,hp,hr,h⟩ refine ⟨fun he => hpr (Fin.ext he),?_⟩ intro i hi let j : Fin n := ⟨i,hi⟩ change Expression.defectAtValue j.val ((p.val,r.val),stateEncode S)=true by_cases hjp : j=p · subst p simpa only [Expression.defectAtValue,ite_true,emptyValue_source,decide_eq_true_eq] using hp · by_cases hjr : j=r · subst r have hne : j.val≠p.val := fun he => hjp (Fin.ext he) simpa only [Expression.defectAtValue,hne,ite_false,ite_true,fullValue_source,decide_eq_true_eq] using hr · have hip : j.val≠p.val := fun he => hjp (Fin.ext he) have hir : j.val≠r.val := fun he => hjr (Fin.ext he) simpa only [Expression.defectAtValue,hip,hir,ite_false,singleValue_source,decide_eq_true_eq] using h j hjp hjr lemma defectCode_source {n : ℕ} (O : IndependenceOracle n) (S : Set (Fin n⊕Fin n)) (p r : Fin n) : run O Expression.defectCode ((p.val,r.val),stateEncode S)= some (decide (DefectState (pairedSlots n) (slotPair p) (slotPair r) S)) := by rw [Expression.run_defectCode,defectValue_source] abbrev SampleData := DataType.list StateData abbrev HistoryData := DataType.list SampleData namespace Expression def countWith {a b} (p : Expression (.prod a b) .bool) : Expression (.prod (.list a) b) .nat := filterWith p >>> listLength lemma run_countWith {n : ℕ} (O : IndependenceOracle n) {a b} (p : Expression (.prod a b) .bool) (f : Value a → Value b → Bool) (hp : ∀ x z,run O p (x,z)=some (f x z)) (xs : List (Value a)) (z : Value b) : run O (countWith p) (xs,z)=some (xs.countP (fun x => f x z)) := by rw [countWith,run_compose,run_filterWith O p f hp,Option.bind_some,run_listLength] simp only [List.countP_eq_length_filter] def countPlainCode : Expression SampleData .nat := both ident (constant (b:=.unit) ()) >>> countWith (fst >>> plainCode) def countDefectCode : Expression (.prod SampleData NN) .nat := countWith (swap >>> defectCode) def countPlainValue (xs : List (Word×Word)) : ℕ := xs.countP plainValue def countDefectValue (xs : List (Word×Word)) (p r : ℕ) : ℕ := xs.countP (fun S => defectValue p r S) lemma run_countPlainCode {n : ℕ} (O : IndependenceOracle n) (xs : List (Word×Word)) : run O countPlainCode xs=some (countPlainValue xs) := by change run O (countWith (fst (b:=.unit) >>> plainCode)) (xs,())=_ exact run_countWith (a:=StateData) (b:=.unit) O _ (fun x (_ : Unit) => plainValue x) (fun x _ => run_plainCode O x) xs () lemma run_countDefectCode {n : ℕ} (O : IndependenceOracle n) (xs : List (Word×Word)) (p r : ℕ) : run O countDefectCode (xs,(p,r))=some (countDefectValue xs p r) := by exact run_countWith (a:=StateData) (b:=NN) O _ (fun S u => defectValue u.1 u.2 S) (fun S u => run_defectCode O u.1 u.2 S) xs (p,r) def learningRatioCode : Expression (.prod SampleData NN) NN := both (fst >>> countPlainCode) countDefectCode >>> normalizeRat def learningRatio (xs : List (Word×Word)) (p r : ℕ) : ℚ := (countPlainValue xs:ℚ)/countDefectValue xs p r lemma learningRatio_nonneg (xs : List (Word×Word)) (p r : ℕ) : 0≤learningRatio xs p r := by unfold learningRatio; positivity lemma run_learningRatio {n : ℕ} (O : IndependenceOracle n) (xs : List (Word×Word)) (p r : ℕ) : run O learningRatioCode (xs,(p,r))=some (rationalPair (learningRatio xs p r)) := by simp only [learningRatioCode,run_compose,run_both,run_fst,Option.bind_some] rw [run_countPlainCode,run_countDefectCode] exact run_normalizeRat_pair O _ _ def weightStep : Expression (.prod SampleData (.prod NN NN)) (.prod NN NN) := both (snd >>> fst) (applyIf (snd >>> fst >>> natEqual) (both (snd >>> snd) (both fst (snd >>> fst) >>> learningRatioCode) >>> ratMul) (snd >>> snd)) def weightUpdate (p r : ℕ) (xs : List (Word×Word)) (q : ℚ) : ℚ := if p=r then q else q*learningRatio xs p r lemma weightUpdate_nonneg (p r : ℕ) (xs : List (Word×Word)) (q : ℚ) (hq : 0≤q) : 0≤weightUpdate p r xs q := by unfold weightUpdate split_ifs · exact hq · exact mul_nonneg hq (learningRatio_nonneg xs p r) lemma run_weightStep {n : ℕ} (O : IndependenceOracle n) (p r : ℕ) (xs : List (Word×Word)) (q : ℚ) (hq : 0≤q) : run O weightStep (xs,((p,r),rationalPair q))=some ((p,r),rationalPair (weightUpdate p r xs q)) := by simp only [weightStep,run_both,run_compose,run_fst,run_snd,Option.bind_some,run_applyIf] rw [run_natEqual] by_cases hpr : p=r · subst p; simp only [decide_true,Option.bind_some,ite_true,Option.map_some,weightUpdate] · simp only [hpr,decide_false,Option.bind_some,Option.map_some,Bool.false_eq_true,ite_false] rw [run_learningRatio] simp only [Option.bind_some,Option.map_some] rw [run_ratMul O q _ hq (learningRatio_nonneg xs p r)] simp only [Option.map_some,weightUpdate,hpr,ite_false] def historyWeightValue (p r : ℕ) (h : List (List (Word×Word))) : ℚ := h.foldl (fun q xs => weightUpdate p r xs q) 4 def historyWeightCode : Expression (.prod HistoryData NN) NN := both fst (both snd (constant (b:=NN) (4,1))) >>> fold weightStep >>> snd lemma fold_weightStep {n : ℕ} (O : IndependenceOracle n) (p r : ℕ) (h : List (List (Word×Word))) (q : ℚ) (hq : 0≤q) : foldValue (run O weightStep) h ((p,r),rationalPair q)=some ((p,r),rationalPair (h.foldl (fun q xs => weightUpdate p r xs q) q)) := by induction h generalizing q with | nil => rfl | cons xs h ih => rw [foldValue,run_weightStep O p r xs q hq,Option.bind_some] exact ih _ (weightUpdate_nonneg p r xs q hq) lemma run_historyWeightCode {n : ℕ} (O : IndependenceOracle n) (p r : ℕ) (h : List (List (Word×Word))) : run O historyWeightCode (h,(p,r))=some (rationalPair (historyWeightValue p r h)) := by change ((foldValue (run O weightStep) h ((p,r),rationalPair 4)).bind fun z => some z.2)=_ rw [fold_weightStep O p r h 4 (by norm_num)] rfl end Expression noncomputable def sampleEncode {n : ℕ} (xs : List (Set (Fin n⊕Fin n))) : Value SampleData := xs.map stateEncode noncomputable def historyEncode {n : ℕ} (h : List (List (Set (Fin n⊕Fin n)))) : Value HistoryData := h.map sampleEncode lemma countPlainValue_source {n : ℕ} (xs : List (Set (Fin n⊕Fin n))) : Expression.countPlainValue (sampleEncode xs)=xs.countP (fun S => decide (PlainState (pairedSlots n) S)) := by simp only [Expression.countPlainValue,sampleEncode,List.countP_map,plainValue_source,Function.comp_def] lemma countDefectValue_source {n : ℕ} (xs : List (Set (Fin n⊕Fin n))) (p r : Fin n) : Expression.countDefectValue (sampleEncode xs) p.val r.val= xs.countP (fun S => decide (DefectState (pairedSlots n) (slotPair p) (slotPair r) S)) := by simp only [Expression.countDefectValue,sampleEncode,List.countP_map,defectValue_source,Function.comp_def] lemma weightUpdate_source {n : ℕ} (xs : List (Set (Fin n⊕Fin n))) (p r : Fin n) (w : ((Fin n⊕Fin n)×(Fin n⊕Fin n)) → ((Fin n⊕Fin n)×(Fin n⊕Fin n)) → ℚ) : Expression.weightUpdate p.val r.val (sampleEncode xs) (w (slotPair p) (slotPair r))= rationalLearn (pairedSlots n) w xs (slotPair p) (slotPair r) := by unfold Expression.weightUpdate rationalLearn by_cases hpr : p=r · subst p; simp · have hv : p.val≠r.val := fun he => hpr (Fin.ext he) have hs : slotPair p≠slotPair r := fun he => hpr ((slotPair_inj p r).mp he) rw [ite_eq_right hv,ite_eq_left ⟨slotPair_mem p,slotPair_mem r,hs⟩,rationalTypeRatio] rw [Expression.learningRatio,countPlainValue_source,countDefectValue_source] lemma historyWeight_source {n : ℕ} (h : List (List (Set (Fin n⊕Fin n)))) (p r : Fin n) : Expression.historyWeightValue p.val r.val (historyEncode h)= rationalHistory (pairedSlots n) id h (slotPair p) (slotPair r) := by have hf : ∀ (l : List (List (Set (Fin n⊕Fin n)))) (w : ((Fin n⊕Fin n)×(Fin n⊕Fin n)) → ((Fin n⊕Fin n)×(Fin n⊕Fin n)) → ℚ), (historyEncode l).foldl (fun q xs => Expression.weightUpdate p.val r.val xs q) (w (slotPair p) (slotPair r))= (l.foldl (fun w xs => rationalLearn (pairedSlots n) w xs) w) (slotPair p) (slotPair r) := by intro l induction l with | nil => intro w; rfl | cons xs l ih => intro w change (historyEncode l).foldl _ (Expression.weightUpdate p.val r.val (sampleEncode xs) (w (slotPair p) (slotPair r)))=_ rw [weightUpdate_source] exact ih _ exact hf h (fun _ _ => 4) lemma historyWeightCode_source {n : ℕ} (O : IndependenceOracle n) (h : List (List (Set (Fin n⊕Fin n)))) (p r : Fin n) : run O Expression.historyWeightCode (historyEncode h,(p.val,r.val))= some (rationalPair (rationalHistory (pairedSlots n) id h (slotPair p) (slotPair r))) := by rw [Expression.run_historyWeightCode,historyWeight_source] namespace Expression def listAppend {a} : Expression (.prod (.list a) (.list a)) (.list a) := onLeft listReverse >>> fold cons lemma run_listAppend {n : ℕ} (O : IndependenceOracle n) {a} (xs ys : List (Value a)) : run O listAppend (xs,ys)=some (xs++ys) := by have hf : ∀ (us vs : List (Value a)),foldValue (run O cons) us vs=some (us.reverse++vs) := by intro us induction us with | nil => intro vs; rfl | cons u us ih => intro vs; simpa [foldValue,run,List.reverse_cons,List.append_assoc] using ih (u::vs) simp only [listAppend,onLeft,run_compose,run_both,run_fst,run_snd,Option.bind_some] rw [run_listReverse] simp only [Option.bind_some,Option.map_some] change foldValue (run O cons) xs.reverse ys=_ rw [hf,List.reverse_reverse] def productStep {a b} : Expression (.prod a (.prod (.list (.prod a b)) (.list b))) (.prod (.list (.prod a b)) (.list b)) := both (both (snd >>> fst) (both (snd >>> snd) fst >>> mapWith swap) >>> listAppend) (snd >>> snd) def productCode {a b} : Expression (.prod (.list a) (.list b)) (.list (.prod a b)) := both fst (both (constant []) snd) >>> fold productStep >>> fst lemma run_productStep {n : ℕ} (O : IndependenceOracle n) {a b} (x : Value a) (zs : List (Value a × Value b)) (ys : List (Value b)) : run O productStep (x,(zs,ys))=some (zs++ys.map (fun y => (x,y)),ys) := by simp only [productStep,run_both,run_compose,run_fst,run_snd,Option.bind_some,Option.map_some] rw [run_mapWith O swap (fun y x => (x,y)) (fun _ _ => rfl)] simp only [Option.map_some,Option.bind_some] rw [run_listAppend] rfl lemma run_productCode {n : ℕ} (O : IndependenceOracle n) {a b} (xs : List (Value a)) (ys : List (Value b)) : run O productCode (xs,ys)=some ((xs ×ˢ ys)) := by have hf : ∀ (us : List (Value a)) (acc : List (Value a × Value b)), foldValue (run O productStep) us (acc,ys)=some (acc++(us ×ˢ ys),ys) := by intro us induction us with | nil => intro acc; simp [foldValue] | cons u us ih => intro acc rw [foldValue,run_productStep,Option.bind_some,ih] simp [List.product_cons,List.append_assoc] change ((foldValue (run O productStep) xs ([],ys)).bind fun z => some z.1)=_ rw [hf] rfl def indexPairs : Expression .nat (.list NN) := both rangeCode rangeCode >>> productCode lemma run_indexPairs {n : ℕ} (O : IndependenceOracle n) (k : ℕ) : run O indexPairs k=some ((List.range k) ×ˢ (List.range k)) := by simp only [indexPairs,run_compose,run_both] rw [run_rangeCode] simp only [Option.bind_some,Option.map_some] exact run_productCode O _ _ end Expression open Expression lemma controlled_listAppend {a : DataType} : Controlled (listAppend (a:=a)) := by unfold listAppend apply controlled_compose · exact controlled_onLeft _ controlled_listReverse · apply controlled_fold (Expression.cons (a:=a)) (controlled_atomic _ trivial) (.mul (.constant 2) .input) intro n O xs z pre post he y hy have hh := foldValue_eq_foldl (run O (cons (a:=a))) (fun z x => x::z) (fun _ _ => rfl) pre z rw [hh] at hy cases hy rw [List.foldl_flip_cons_eq_append',width_list_append,width_list_reverse] have hp : width (a:=.list a) pre≤width (a:=.list a) xs := by rw [he,width_list_append]; omega rw [width_pair (a:=.list a) (b:=.list a)] dsimp [SizePolynomial.eval] omega lemma width_list_map_pair {a b : DataType} (x : Value a) (ys : List (Value b)) : width (a:=.list (.prod a b)) (ys.map (fun y => (x,y)))≤ 4*(width x+1)*(width (a:=.list b) ys+1) := by have he : width (a:=.list (.prod a b)) (ys.map (fun y => (x,y)))= (4*width x+2)*ys.length+width (a:=.list b) ys := by induction ys with | nil => rfl | cons y ys ih => simp only [List.map_cons,width_cons (a:=.prod a b),width_pair (a:=a) (b:=b),ih, List.length_cons,width_cons (a:=b)] ring rw [he] have hl := list_length_le_width ys nlinarith lemma width_list_product {a b : DataType} (xs : List (Value a)) (ys : List (Value b)) : width (a:=.list (.prod a b)) (xs ×ˢ ys)≤ 8*(width (a:=.list a) xs+1)*(width (a:=.list b) ys+1) := by have hh : width (a:=.list (.prod a b)) (xs ×ˢ ys)≤ 4*width (a:=.list a) xs*(width (a:=.list b) ys+1) := by induction xs with | nil => simp only [List.nil_product,width_nil (a:=.prod a b)]; omega | cons x xs ih => rw [List.product_cons,width_list_append (a:=.prod a b)] have hx := width_list_map_pair x ys rw [width_cons (a:=a)] nlinarith nlinarith lemma controlled_productStep {a b : DataType} : Controlled (productStep (a:=a) (b:=b)) := by have hm := controlled_mapWith (Expression.swap (a:=b) (b:=a)) controlled_swap have ha := controlled_listAppend (a:=.prod a b) unfold productStep control lemma fold_productStep {n : ℕ} (O : IndependenceOracle n) {a b : DataType} (xs : List (Value a)) (zs : List (Value a×Value b)) (ys : List (Value b)) : foldValue (run O (productStep (a:=a) (b:=b))) xs (zs,ys)=some (zs++(xs ×ˢ ys),ys) := by induction xs generalizing zs with | nil => simp [foldValue] | cons x xs ih => rw [foldValue,run_productStep,Option.bind_some,ih] simp [List.product_cons,List.append_assoc] lemma controlled_productCode {a b : DataType} : Controlled (productCode (a:=a) (b:=b)) := by unfold productCode apply controlled_compose · control · apply controlled_compose · apply controlled_fold productStep controlled_productStep (.mul (.constant 32) (.mul (.add .input (.constant 1)) (.add .input (.constant 1)))) intro n O xs z pre post he y hy rcases z with ⟨zs,ys⟩ rw [fold_productStep] at hy cases hy have hp : width (a:=.list a) pre≤width (a:=.list a) xs := by rw [he,width_list_append]; omega have hb := width_list_product pre ys rw [width_pair (a:=.list (.prod a b)) (b:=.list b),width_list_append, width_pair (a:=.list a) (b:=.prod (.list (.prod a b)) (.list b)), width_pair (a:=.list (.prod a b)) (b:=.list b)] dsimp [SizePolynomial.eval] nlinarith · control lemma controlled_wordGet : Controlled wordGet := by have hg := controlled_getD (a:=.bool) unfold wordGet control lemma controlled_wordNot : Controlled wordNot := by have hm := controlled_mapWith (c:=.unit) (fst >>> boolNot) (by apply controlled_compose; exact controlled_atomic _ trivial; exact controlled_boolNot) have hf := controlled_fromList unfold wordNot control lemma controlled_wordCountStep : Controlled wordCountStep := by unfold wordCountStep; control lemma fold_wordCount_bound {n : ℕ} (O : IndependenceOracle n) (xs : List Bool) (z y : ℕ) (hy : foldValue (run O wordCountStep) xs z=some y) : y≤z+xs.length := by induction xs generalizing z with | nil => cases hy; simp | cons b xs ih => cases b with | false => have hh := ih z hy; simp only [List.length_cons]; omega | true => have hh := ih (z+1) hy; simp only [List.length_cons]; omega lemma controlled_wordCount : Controlled wordCount := by unfold wordCount apply controlled_compose · control · apply controlled_compose · control · apply controlled_fold wordCountStep controlled_wordCountStep (.mul (.constant 2) .input) intro n O xs z pre post he y hy have hh := bits_length_mono (fold_wordCount_bound O pre z y hy) have ha := bits_length_add z pre.length have hp : pre.length≤xs.length := by rw [he,List.length_append]; omega have hl := bits_length_le_value pre.length rw [width_nat,width_pair (a:=.list .bool) (b:=.nat),width_nat,width_list_bool] dsimp [SizePolynomial.eval] omega lemma controlled_deficiency : Controlled deficiencyCode := by have hl := controlled_wordLength have hc := controlled_wordCount have hn := controlled_wordNot have hs := controlled_natSub unfold deficiencyCode control open Expression lemma controlled_normalizeRat : Controlled normalizeRat := by have hg := controlled_gcd unfold normalizeRat control lemma controlled_ratCross : Controlled ratCross := by unfold ratCross; control lemma controlled_ratAdd : Controlled ratAdd := by have hg := controlled_normalizeRat unfold ratAdd control lemma controlled_ratMul : Controlled ratMul := by have hg := controlled_normalizeRat unfold ratMul control lemma controlled_ratDiv : Controlled ratDiv := by have hg := controlled_normalizeRat unfold ratDiv control lemma controlled_ratLess : Controlled ratLess := by unfold ratLess; control lemma controlled_ratMinOne : Controlled ratMinOne := by unfold ratMinOne; control lemma iterateM_succ_last {A : Type*} (f : A → Option A) (k : ℕ) (x : A) : iterateM f (k+1) x=(iterateM f k x).bind f := by induction k generalizing x with | zero => simp [iterateM] | succ k ih => simp only [iterateM,Option.bind_assoc] congr 1 funext y exact ih y open Expression open scoped Classical namespace Effect lemma realizes_repeat_succ_last {n : ℕ} (O : IndependenceOracle n) {A B : Type*} {a} (p : Effect a a) (ea : A → Value a) (eb : B → Value a) (k : ℕ) (x : Value a) (t : DrawTree A) (f : A → DrawTree B) (hp : Realizes O (repeatCode p) ea (k,x) t) (hq : ∀ y,Realizes O p eb (ea y) (f y)) : Realizes O (repeatCode p) eb (k+1,x) (t.bind f) := by intro bank rw [run_repeat,iterateM_succ_last,←run_repeat,hp,Option.bind_some,bankEval_bind] cases ht : bankEval t bank with | mk out rest => cases out with | none => rfl | some y => exact hq y rest lemma law_repeat_succ_last {n : ℕ} (O : IndependenceOracle n) {A B : Type*} {a} (p : Effect a a) (ea : A → Value a) (eb : B → Value a) (k : ℕ) (x : Value a) (t : DrawTree A) (f : A → DrawTree B) (hp : RealizesLaw O (repeatCode p) ea (k,x) t) (hq : ∀ y,RealizesLaw O p eb (ea y) (f y)) : RealizesLaw O (repeatCode p) eb (k+1,x) (t.bind f) := by classical rcases hp with ⟨u,hu,hp⟩ choose g hg hq using hq exact ⟨u.bind g,hu.bind hg,realizes_repeat_succ_last O p ea eb k x u g hp hq⟩ def phaseRepeat {A : Type*} (f : ℕ → A → DrawTree (Option A)) : ℕ → A → DrawTree (Option A) | 0,x => .leaf (some x) | k+1,x => (phaseRepeat f k x).optionBind (f (k+1)) lemma phaseRepeat_bind {A B : Type*} (f : ℕ → A → DrawTree (Option A)) (t : DrawTree B) (g : B → A) (k : ℕ) : (t.bind (fun x => phaseRepeat f (k+1) (g x)))= (t.bind (fun x => phaseRepeat f k (g x))).optionBind (f (k+1)) := by simp only [phaseRepeat,DrawTree.optionBind,DrawTree.bind_assoc] lemma law_phaseRepeat {n : ℕ} (O : IndependenceOracle n) {A : Type*} {a} (p : Effect a (Optional a)) (e : ℕ → A → Value a) (f : ℕ → A → DrawTree (Option A)) (hp : ∀ j x,RealizesLaw O p (optionEncode (e (j+1))) (e j x) (f (j+1) x)) (k : ℕ) (x : A) : RealizesLaw O (repeatCode (optionContinue p)) (optionEncode (e k)) (k,optionEncode (e 0) (some x)) (phaseRepeat f k x) := by induction k with | zero => exact ⟨.leaf (some x),.leaf (some x),fun _ => rfl⟩ | succ k ih => apply law_repeat_succ_last O (optionContinue p) (optionEncode (e k)) _ k _ _ _ ih intro y exact law_optionContinue O p (e k) (e (k+1)) (f (k+1)) y (hp k) def hitStepCode {a} (step : Effect a a) (test : Expression a .bool) : Effect (.prod a .bool) (.prod a .bool) := choose snd (map (precompose fst step) (both ident test)) (pure ident) def hitFinish {a} : Expression (.prod a .bool) (Optional a) := applyIf snd (constant (optionalValue a none)) (both (constant true) fst) def hittingCode {a} (step : Effect a a) (test : Expression a .bool) : Effect (.prod .nat a) (Optional a) := precompose (both fst (both snd (constant false))) (map (repeatCode (hitStepCode step test)) hitFinish) abbrev SearchState (X : Type*) (P : X → Prop) := X ⊕ FiniteChain.Inside P noncomputable def searchStep {X : Type*} (step : X → DrawTree X) (P : X → Prop) : SearchState X P → DrawTree (SearchState X P) | .inl x => (step x).map (fun y => if hy : P y then .inr ⟨y,hy⟩ else .inl y) | .inr y => .leaf (.inr y) def searchFinish {X : Type*} {P : X → Prop} : SearchState X P → Option (FiniteChain.Inside P) | .inl _ => none | .inr y => some y def searchEncode {X : Type*} {P : X → Prop} {a} (e : X → Value a) : SearchState X P → Value (.prod a .bool) | .inl x => (e x,false) | .inr y => (e y.val,true) lemma searchRepeat_done {X : Type*} (step : X → DrawTree X) (P : X → Prop) (k : ℕ) (y : FiniteChain.Inside P) : treeRepeat (searchStep step P) k (.inr y)=.leaf (.inr y) := by induction k with | zero => rfl | succ k ih => exact ih lemma searchRepeat_finish {X : Type*} [Fintype X] (step : X → DrawTree X) (P : X → Prop) (k : ℕ) (x : X) : (treeRepeat (searchStep step P) k (.inl x)).map searchFinish=hittingTree step P k x := by induction k generalizing x with | zero => rfl | succ k ih => simp only [treeRepeat,searchStep,DrawTree.map_bind,DrawTree.bind_map,hittingTree] congr 1 funext y by_cases hy : P y · rw [dite_eq_left hy,searchRepeat_done,dite_eq_left hy]; rfl · rw [dite_eq_right hy,ih,dite_eq_right hy] lemma law_hitStep {n : ℕ} (O : IndependenceOracle n) {X : Type*} {a} (step : Effect a a) (test : Expression a .bool) (e : X → Value a) (f : X → DrawTree X) (P : X → Prop) (hs : ∀ x,RealizesLaw O step e (e x) (f x)) (ht : ∀ x,run O test (e x)=some (decide (P x))) (u : SearchState X P) : RealizesLaw O (hitStepCode step test) (searchEncode e) (searchEncode e u) (searchStep f P u) := by unfold hitStepCode cases u with | inl x => apply law_choose O _ _ _ _ _ _ false rfl change RealizesLaw O (map (precompose fst step) (both ident test)) _ _ _ apply law_map O _ _ e _ _ _ _ · exact law_precompose O fst step _ _ _ _ rfl (hs x) · intro y rw [run_both,run_ident,Option.bind_some,ht] by_cases hy : P y · simp only [hy,dite_eq_left,decide_true,Option.map_some]; rfl · simp only [hy,decide_false,Option.map_some]; rfl | inr y => apply law_choose O _ _ _ _ _ _ true rfl change RealizesLaw O (pure ident) (searchEncode e) _ (.leaf (.inr y)) exact (realizes_pure O ident (searchEncode e) _ (Sum.inr y) rfl).law lemma law_hitting {n : ℕ} (O : IndependenceOracle n) {X : Type*} [Fintype X] {a} (step : Effect a a) (test : Expression a .bool) (e : X → Value a) (f : X → DrawTree X) (P : X → Prop) (hs : ∀ x,RealizesLaw O step e (e x) (f x)) (ht : ∀ x,run O test (e x)=some (decide (P x))) (k : ℕ) (x : X) : RealizesLaw O (hittingCode step test) (optionEncode (fun y : FiniteChain.Inside P => e y.val)) (k,e x) (hittingTree f P k x) := by unfold hittingCode apply law_precompose O _ _ _ _ (k,searchEncode e (.inl x : SearchState X P)) _ rfl rw [←searchRepeat_finish] apply law_map O _ _ (searchEncode e) _ _ _ searchFinish · exact law_repeat O _ _ _ (law_hitStep O step test e f P hs ht) k (.inl x) · intro u cases u <;> rfl end Effect open Expression namespace Expression def optionMapCode {a b} (p : Expression a b) : Expression (Optional a) (Optional b) := applyIf fst (constant (optionalValue b none)) (both (constant true) (snd >>> p)) lemma run_optionMapCode {n : ℕ} (O : IndependenceOracle n) {a b} (p : Expression a b) (f : Value a → Value b) (hp : ∀ x,run O p x=some (f x)) (x : Option (Value a)) : run O (optionMapCode p) (optionalValue a x)=some (optionalValue b (x.map f)) := by cases x with | none => rfl | some x => change ((run O p x).bind fun y => some (true,y))=_ rw [hp]; rfl end Expression namespace Effect lemma law_recode {n : ℕ} (O : IndependenceOracle n) {A : Type*} {a b c} (p : Effect a b) (q : Expression b c) (ea : A → Value b) (eb : A → Value c) (x : Value a) (t : DrawTree A) (hp : RealizesLaw O p ea x t) (hq : ∀ y,run O q (ea y)=some (eb y)) : RealizesLaw O (map p q) eb x t := by have hh := law_map O p q ea eb x t id hp hq simpa only [DrawTree.map,id_eq,DrawTree.bind_leaf] using hh def withContext {a b c} (p : Effect (.prod c a) b) : Effect (.prod c a) (.prod c b) := letIn p (pure (both (fst >>> fst) snd)) lemma law_withContext {n : ℕ} (O : IndependenceOracle n) {A : Type*} {a b c} (p : Effect (.prod c a) b) (e : A → Value b) (ctx : Value c) (x : Value a) (t : DrawTree A) (hp : RealizesLaw O p e (ctx,x) t) : RealizesLaw O (withContext p) (fun y => (ctx,e y)) (ctx,x) t := by unfold withContext rw [←DrawTree.bind_leaf t] apply law_letIn O p _ e _ _ t DrawTree.leaf hp intro y exact (realizes_pure O _ _ _ y rfl).law lemma law_optionMap {n : ℕ} (O : IndependenceOracle n) {A B : Type*} {a b c} (p : Effect a (Optional b)) (q : Expression b c) (ea : A → Value b) (eb : B → Value c) (x : Value a) (t : DrawTree (Option A)) (f : A → B) (hp : RealizesLaw O p (optionEncode ea) x t) (hq : ∀ y,run O q (ea y)=some (eb (f y))) : RealizesLaw O (map p (optionMapCode q)) (optionEncode eb) x (t.map (Option.map f)) := by apply law_map O p _ (optionEncode ea) (optionEncode eb) x t _ hp intro y cases y with | none => rfl | some y => change ((run O q (ea y)).bind fun z => some (true,z))=_ rw [hq]; rfl lemma law_optionRecode {n : ℕ} (O : IndependenceOracle n) {A : Type*} {a b c} (p : Effect a (Optional b)) (q : Expression b c) (ea : A → Value b) (eb : A → Value c) (x : Value a) (t : DrawTree (Option A)) (hp : RealizesLaw O p (optionEncode ea) x t) (hq : ∀ y,run O q (ea y)=some (eb y)) : RealizesLaw O (map p (optionMapCode q)) (optionEncode eb) x t := by apply law_recode O p _ (optionEncode ea) (optionEncode eb) x t hp intro y cases y with | none => rfl | some y => change ((run O q (ea y)).bind fun z => some (true,z))=_ rw [hq]; rfl end Effect open scoped Classical namespace Expression def defectPairsValue (S : Word×Word) : List (ℕ×ℕ) := ((List.range S.1.length) ×ˢ (List.range S.1.length)).filter (fun pr => defectValue pr.1 pr.2 S) def defectPairsCode : Expression StateData (.list NN) := both (fst >>> wordLength >>> indexPairs) ident >>> filterWith defectCode lemma run_defectPairsCode {n : ℕ} (O : IndependenceOracle n) (S : Word×Word) : run O defectPairsCode S=some (defectPairsValue S) := by simp only [defectPairsCode,run_compose,run_both,run_fst,run_ident,Option.bind_some] rw [run_wordLength,Option.bind_some,run_indexPairs] simp only [Option.bind_some,Option.map_some] exact run_filterWith (a:=NN) (b:=StateData) O defectCode (fun pr S => defectValue pr.1 pr.2 S) (fun pr S => run_defectCode O pr.1 pr.2 S) _ S def chainValue (S : Word×Word) : Bool := plainValue S || decide ((defectPairsValue S).length≠0) def chainCode : Expression StateData .bool := both plainCode (defectPairsCode >>> listLength >>> natEqZero >>> boolNot) >>> boolOr lemma run_chainCode {n : ℕ} (O : IndependenceOracle n) (S : Word×Word) : run O chainCode S=some (chainValue S) := by simp only [chainCode,run_compose,run_both] rw [run_plainCode,run_defectPairsCode] simp only [Option.bind_some,run_compose,run_listLength,run_natEqZero,run_boolNot,Option.map_some] rw [run_boolOr] simp only [chainValue,decide_not] def multiplierValue (h : List (List (Word×Word))) (S : Word×Word) : ℚ := if (defectPairsValue S).length=0 then 1 else historyWeightValue ((defectPairsValue S).headD (0,0)).1 ((defectPairsValue S).headD (0,0)).2 h def multiplierCode : Expression (.prod HistoryData StateData) NN := letIn (snd >>> defectPairsCode) (applyIf (snd >>> listLength >>> natEqZero) (both (fst >>> fst) (both snd (constant (0,0)) >>> headD) >>> historyWeightCode) (constant (1,1))) lemma run_multiplierCode {n : ℕ} (O : IndependenceOracle n) (h : List (List (Word×Word))) (S : Word×Word) : run O multiplierCode (h,S)=some (rationalPair (multiplierValue h S)) := by simp only [multiplierCode,run_letIn,run_compose,run_snd,Option.bind_some] rw [run_defectPairsCode] simp only [Option.bind_some,run_applyIf,run_compose,run_snd,run_listLength,run_natEqZero] by_cases he : (defectPairsValue S).length=0 · simp only [he,decide_true,ite_true,multiplierValue,run_constant] rfl · simp only [he,decide_false,Option.bind_some,Bool.false_eq_true,ite_false,multiplierValue, run_compose,run_both,run_fst,run_snd,run_constant,Option.map_some] rw [run_headD] simp only [Option.map_some,Option.bind_some] exact run_historyWeightCode O _ _ h end Expression lemma mem_defectPairsValue {n : ℕ} (S : Set (Fin n⊕Fin n)) (p r : ℕ) : (p,r)∈Expression.defectPairsValue (stateEncode S) ↔ ∃ (hp : p exact False.elim (hl hh) | cons a l => simp obtain ⟨hp,hr,hd⟩ := (mem_defectPairsValue S (l.headD (0,0)).1 (l.headD (0,0)).2).mp hm have hex : ∃ p r,DefectState (pairedSlots n) p r S := ⟨_,_,hd⟩ rw [ite_eq_right he,dite_eq_left hex,historyWeight_source h ⟨_,hp⟩ ⟨_,hr⟩] have hh := hex.choose_spec.choose_spec.unique hd exact congrArg₂ (rationalHistory (pairedSlots n) id h) hh.1.symm hh.2.symm namespace Expression @[simp] lemma run_append {n : ℕ} (O : IndependenceOracle n) (S : Word×Word) : run O append S=some (S.1++S.2) := rfl def updateAt : Expression (.prod .nat (.prod .word (.prod .nat .bool))) .bool := applyIf (both fst (snd >>> snd >>> fst) >>> natEqual) (both (snd >>> fst) fst >>> wordGet) (snd >>> snd >>> snd) def updateWord : Expression (.prod .word (.prod .nat .bool)) .word := both (fst >>> wordLength >>> rangeCode) ident >>> mapWith updateAt >>> fromList lemma run_updateAt {n : ℕ} (O : IndependenceOracle n) (i : ℕ) (w : Word) (j : ℕ) (b : Bool) : run O updateAt (i,(w,(j,b)))=some (if i=j then b else w[i]?.getD false) := by simp only [updateAt,run_applyIf,run_compose,run_both,run_fst,run_snd,Option.bind_some,Option.map_some] rw [run_natEqual,run_wordGet] by_cases h : i=j <;> simp [h] lemma run_updateWord {n : ℕ} (O : IndependenceOracle n) (w : Word) (j : ℕ) (b : Bool) : run O updateWord (w,(j,b))=some (w.set j b) := by simp only [updateWord,run_compose,run_both,run_fst,run_ident,Option.bind_some] rw [run_wordLength,Option.bind_some,run_rangeCode] simp only [Option.bind_some,Option.map_some,run_compose] rw [run_mapWith (a:=.nat) (b:=.bool) (c:=.prod .word (.prod .nat .bool)) O updateAt (fun i z => if i=z.2.1 then z.2.2 else z.1[i]?.getD false) (fun i z => run_updateAt O i z.1 z.2.1 z.2.2)] simp only [Option.bind_some] rw [run_fromList] congr 1 apply List.ext_getElem · simp · intro i hi hj simp only [List.getElem_map,List.getElem_range,List.getElem_set] rw [List.getElem?_eq_getElem (by simpa using hi)] simp only [Option.getD_some] by_cases he : i=j · simp [he] · simp [he,Ne.symm he] def splitWord : Expression (.prod .word .nat) StateData := onLeft toList >>> splitAtCode >>> both (fst >>> fromList) (snd >>> fromList) lemma run_splitWord {n : ℕ} (O : IndependenceOracle n) (w : Word) (k : ℕ) : run O splitWord (w,k)=some (w.take k,w.drop k) := by change ((run O (splitAtCode (a:=.bool)) (w,k)).bind (run O (both (fst >>> fromList) (snd >>> fromList))))=_ rw [run_splitAtCode] simp only [Option.bind_some,run_both,run_compose,run_fst,run_snd] rw [run_fromList,run_fromList] rfl def exchangeWord : Expression (.prod .word NN) .word := letIn (both fst (both (snd >>> fst) (constant false)) >>> updateWord) (both snd (both (fst >>> snd >>> snd) (constant true)) >>> updateWord) lemma run_exchangeWord {n : ℕ} (O : IndependenceOracle n) (w : Word) (a b : ℕ) : run O exchangeWord (w,(a,b))=some ((w.set a false).set b true) := by simp only [exchangeWord,run_letIn,run_compose,run_both,run_fst,run_snd,run_constant, Option.bind_some,Option.map_some] rw [run_updateWord] simp only [Option.bind_some] exact run_updateWord O _ _ _ def exchangeSetCode : Expression (.prod StateData NN) StateData := both (both (fst >>> append) snd >>> exchangeWord) (fst >>> fst >>> wordLength) >>> splitWord lemma run_exchangeSetCode {n : ℕ} (O : IndependenceOracle n) (S : Word×Word) (a b : ℕ) : run O exchangeSetCode (S,(a,b))=some ((((S.1++S.2).set a false).set b true).take S.1.length, (((S.1++S.2).set a false).set b true).drop S.1.length) := by simp only [exchangeSetCode,run_compose,run_both,run_fst,run_snd,run_append,Option.bind_some,Option.map_some] rw [run_exchangeWord,run_wordLength] simp only [Option.bind_some,Option.map_some] exact run_splitWord O _ _ end Expression open scoped Classical noncomputable def combinedEncode {n : ℕ} (S : Set (Fin n⊕Fin n)) : Word := (stateEncode S).1++(stateEncode S).2 def position {n : ℕ} (i : Fin n⊕Fin n) : ℕ := (finSumFinEquiv i).val lemma position_lt {n : ℕ} (i : Fin n⊕Fin n) : position i finSumFinEquiv.injective (Fin.ext h),fun h => congrArg position h⟩ @[simp] lemma combinedEncode_length {n : ℕ} (S : Set (Fin n⊕Fin n)) : (combinedEncode S).length=n+n := by simp [combinedEncode] lemma combinedEncode_get {n : ℕ} (S : Set (Fin n⊕Fin n)) (i : Fin n⊕Fin n) : (combinedEncode S)[position i]?.getD false=decide (i∈S) := by cases i with | inl i => simp only [combinedEncode,position,finSumFinEquiv,Equiv.coe_fn_mk] rw [List.getElem?_append_left (by simp)] exact stateEncode_get_left S i | inr i => simp [combinedEncode,stateEncode,position,finSumFinEquiv,i.isLt] lemma combinedEncode_update {n : ℕ} (S : Set (Fin n⊕Fin n)) (i : Fin n⊕Fin n) (b : Bool) : (combinedEncode S).set (position i) b=combinedEncode (if b then insert i S else S\{i}) := by apply List.ext_getElem · simp · intro k hk hk' let j : Fin n⊕Fin n := finSumFinEquiv.symm ⟨k,by simpa using hk'⟩ have hj : position j=k := by simp [position,j] have ha := combinedEncode_get S j have hb := combinedEncode_get (if b then insert i S else S\{i}) j rw [hj,List.getElem?_eq_getElem (by simpa using hk),Option.getD_some] at ha rw [hj,List.getElem?_eq_getElem hk',Option.getD_some] at hb rw [List.getElem_set,ha,hb] have he : position i=k ↔ i=j := by rw [←hj,position_inj] simp only [he] cases b <;> by_cases hij : i=j <;> simp [hij,eq_comm] lemma exchangeSetCode_source {n : ℕ} (O : IndependenceOracle n) (S : Set (Fin n⊕Fin n)) (a : ExchangeChoice S) : run O Expression.exchangeSetCode (stateEncode S,(position a.1.val,position a.2.val))= some (stateEncode (exchangedSet S a)) := by rw [Expression.run_exchangeSetCode,stateEncode_left_length] change some (((combinedEncode S).set (position a.1.val) false |>.set (position a.2.val) true).take n, ((combinedEncode S).set (position a.1.val) false |>.set (position a.2.val) true).drop n)=_ rw [combinedEncode_update] simp only [Bool.false_eq_true,ite_false] rw [combinedEncode_update] simp only [ite_true] change some ((combinedEncode (exchangedSet S a)).take n,(combinedEncode (exchangedSet S a)).drop n)=_ have hh (x y : Word) : some ((x++y).take x.length,(x++y).drop x.length)=some (x,y) := by simp simpa only [combinedEncode, stateEncode_left_length, Prod.eta] using hh (stateEncode (exchangedSet S a)).1 (stateEncode (exchangedSet S a)).2 open scoped Classical namespace Expression lemma historyWeightValue_nonneg (p r : ℕ) (h : List (List (Word×Word))) : 0≤historyWeightValue p r h := by have hf : ∀ (l : List (List (Word×Word))) (q : ℚ),0≤q → 0≤l.foldl (fun q xs => weightUpdate p r xs q) q := by intro l induction l with | nil => intro q hq; exact hq | cons xs l ih => intro q hq; exact ih _ (weightUpdate_nonneg p r xs q hq) exact hf h 4 (by norm_num) lemma multiplierValue_nonneg (h : List (List (Word×Word))) (S : Word×Word) : 0 ≤ multiplierValue h S := by unfold multiplierValue split_ifs · norm_num · exact historyWeightValue_nonneg _ _ h def rhoCode : Expression .nat NN := applyIf natEqZero (letIn (both ident (constant 2) >>> mul) (both (both snd (constant 1) >>> natSub) snd >>> normalizeRat)) (constant (1,1)) lemma rationalRho_nonneg (n : ℕ) : 0≤rationalRho n := by cases n with | zero => norm_num [rationalRho] | succ n => unfold rationalRho have hh : (1:ℚ) ≤ 2*((n+1:ℕ):ℚ) := by push_cast; linarith [Nat.cast_nonneg (α:=ℚ) n] exact sub_nonneg.mpr ((div_le_one (by positivity : (0:ℚ)<2*((n+1:ℕ):ℚ))).mpr hh) lemma run_rhoCode {n : ℕ} (O : IndependenceOracle n) (m : ℕ) : run O rhoCode m=some (rationalPair (rationalRho m)) := by simp only [rhoCode,run_applyIf,run_natEqZero] by_cases hm : m=0 · subst m; simp only [decide_true,Option.bind_some,ite_true,run_constant] norm_num [rationalPair,rationalRho] · simp only [hm,decide_false,Option.bind_some,Bool.false_eq_true,ite_false] change run O (both (both (snd (a:=.nat) (b:=.nat)) (constant 1) >>> natSub) snd >>> normalizeRat) (m,m*2)=_ simp only [run_compose,run_both,run_snd,run_constant,Option.bind_some,Option.map_some] rw [run_natSub] simp only [Option.bind_some] rw [run_normalizeRat_pair] congr 2 have hp : 1 ≤ m*2 := by omega have hz : (m:ℚ)≠0 := by exact_mod_cast hm rw [Nat.cast_sub hp,Nat.cast_mul,Nat.cast_ofNat,Nat.cast_one] unfold rationalRho field_simp abbrev WeightContext := DataType.prod NN HistoryData abbrev WeightInput := DataType.prod WeightContext StateData def annealCode : Expression WeightInput NN := both (both (snd >>> fst >>> wordLength >>> rhoCode) (fst >>> fst >>> snd) >>> ratPowCode) (both (fst >>> fst >>> fst) snd >>> deficiencyCode) >>> ratPowCode def weightCode : Expression WeightInput NN := both (both (fst >>> snd) snd >>> multiplierCode) annealCode >>> ratMul end Expression lemma rationalHistory_nonnegative {n : ℕ} (h : List (List (Set (Fin n⊕Fin n)))) (p r : (Fin n⊕Fin n)×(Fin n⊕Fin n)) : 0≤rationalHistory (pairedSlots n) id h p r := by have hf : ∀ (l : List (List (Set (Fin n⊕Fin n)))) (w : ((Fin n⊕Fin n)×(Fin n⊕Fin n)) → ((Fin n⊕Fin n)×(Fin n⊕Fin n)) → ℚ), (∀ p r,0≤w p r) → ∀ p r,0≤(l.foldl (fun w xs => rationalLearn (pairedSlots n) w xs) w) p r := by intro l induction l with | nil => intro w hw p r; exact hw p r | cons xs l ih => intro w hw p r apply ih intro a b dsimp only [rationalLearn] split_ifs · rw [rationalTypeRatio] exact mul_nonneg (hw _ _) (div_nonneg (Nat.cast_nonneg _) (Nat.cast_nonneg _)) · exact hw _ _ exact hf h (fun _ _ => 4) (by intros; norm_num) p r lemma annealCode_source {n : ℕ} (M₁ M₂ : Matroid (Fin n)) (O : IndependenceOracle n) (hO : ExactOracles M₁ M₂ O) (hE₁ : M₁.E=Set.univ) (hE₂ : M₂.E=Set.univ) (r j : ℕ) (h : List (List (Set (Fin n⊕Fin n)))) (S : Set (Fin n⊕Fin n)) : run O Expression.annealCode (((r,j),historyEncode h),stateEncode S)= some (rationalPair ((rationalRho n^j)^(oracleDeficiency n r O S))) := by simp only [Expression.annealCode,Expression.run_compose,Expression.run_both, Expression.run_fst,Expression.run_snd,Option.bind_some,Option.map_some] rw [Expression.run_wordLength,stateEncode_left_length] simp only [Option.bind_some] rw [Expression.run_rhoCode] simp only [Option.bind_some] rw [Expression.run_ratPowCode O _ (Expression.rationalRho_nonneg n)] simp only [Option.bind_some] rw [deficiencyCode_source M₁ M₂ O hO hE₁ hE₂ r _ _ (stateEncode_left_length S) (stateEncode_right_length S),stateEncode_repr] simp only [Option.bind_some,Option.map_some] exact Expression.run_ratPowCode O _ (pow_nonneg (Expression.rationalRho_nonneg n) _) _ lemma weightCode_source {n : ℕ} (M₁ M₂ : Matroid (Fin n)) (O : IndependenceOracle n) (hO : ExactOracles M₁ M₂ O) (hE₁ : M₁.E=Set.univ) (hE₂ : M₂.E=Set.univ) (r j : ℕ) (h : List (List (Set (Fin n⊕Fin n)))) (S : Set (Fin n⊕Fin n)) : run O Expression.weightCode (((r,j),historyEncode h),stateEncode S)=some (rationalPair (rationalMultiplier (pairedSlots n) (rationalHistory (pairedSlots n) id h) S* (rationalRho n^j)^(oracleDeficiency n r O S))) := by simp only [Expression.weightCode,Expression.run_compose,Expression.run_both, Expression.run_fst,Expression.run_snd,Option.bind_some,Option.map_some] rw [Expression.run_multiplierCode,multiplierValue_source,annealCode_source M₁ M₂ O hO hE₁ hE₂] simp only [Option.bind_some,Option.map_some] apply Expression.run_ratMul · rw [←multiplierValue_source] exact Expression.multiplierValue_nonneg _ _ · exact pow_nonneg (pow_nonneg (Expression.rationalRho_nonneg n) j) _ open Expression namespace Effect def bernoulliCode : Effect NN .bool := letIn (precompose snd draw) (pure (both snd (fst >>> fst) >>> less)) lemma bernoulliCode_source {n : ℕ} (O : IndependenceOracle n) (q : ℚ) : Realizes O bernoulliCode id (rationalPair q) (DrawTree.bernoulli q) := by have hd : q.den-1+1=q.den := by have hh := q.den_pos; omega have hh : Realizes O draw Fin.val q.den (.draw (q.den-1) DrawTree.leaf) := by simpa only [hd] using realizes_draw O (q.den-1) have hp : Realizes O (precompose (snd (a:=.nat)) draw) Fin.val (rationalPair q) (.draw (q.den-1) DrawTree.leaf) := realizes_precompose (a:=NN) (b:=.nat) (c:=.nat) O snd draw Fin.val (rationalPair q) q.den _ rfl hh change Realizes O (letIn (precompose snd draw) (pure (both snd (fst >>> fst) >>> less))) id (rationalPair q) _ have hr := realizes_letIn O (precompose (snd (a:=.nat)) draw) (pure (both snd (fst >>> fst) >>> less)) Fin.val id (rationalPair q) (.draw (q.den-1) DrawTree.leaf) (fun (i : Fin (q.den-1+1)) => .leaf (decide (i.val realizes_pure O _ id _ _ rfl) exact hr end Effect open Expression open scoped Classical namespace Expression abbrev AcceptanceInput := DataType.prod WeightContext (.prod StateData StateData) def acceptanceCode : Expression AcceptanceInput NN := both (both fst (snd >>> snd) >>> weightCode) (both fst (snd >>> fst) >>> weightCode) >>> ratDiv >>> ratMinOne end Expression lemma acceptanceCode_source {n : ℕ} (M₁ M₂ : Matroid (Fin n)) (O : IndependenceOracle n) (hO : ExactOracles M₁ M₂ O) (hE₁ : M₁.E=Set.univ) (hE₂ : M₂.E=Set.univ) (r j : ℕ) (h : List (List (Set (Fin n⊕Fin n)))) (S T : ChainIndex (pairedSlots n)) : run O acceptanceCode (((r,j),historyEncode h),(stateEncode S.val,stateEncode T.val))=some (rationalPair (rationalAcceptance (pairedSlots n) (rationalHistory (pairedSlots n) id h) (oracleAnneal n r O j) S T)) := by have hn (U : Set (Fin n⊕Fin n)) : 0 ≤ rationalWeight (pairedSlots n) (rationalHistory (pairedSlots n) id h) (oracleAnneal n r O j) U := by unfold rationalWeight apply mul_nonneg · rw [←multiplierValue_source]; exact multiplierValue_nonneg _ _ · exact pow_nonneg (pow_nonneg (rationalRho_nonneg n) j) _ simp only [acceptanceCode,run_compose,run_both,run_fst,run_snd,Option.bind_some,Option.map_some] rw [weightCode_source M₁ M₂ O hO hE₁ hE₂,weightCode_source M₁ M₂ O hO hE₁ hE₂] simp only [Option.bind_some,Option.map_some] change ((run O ratDiv (rationalPair (rationalWeight (pairedSlots n) (rationalHistory (pairedSlots n) id h) (oracleAnneal n r O j) T.val),rationalPair (rationalWeight (pairedSlots n) (rationalHistory (pairedSlots n) id h) (oracleAnneal n r O j) S.val))).bind (run O ratMinOne))=_ rw [run_ratDiv O _ _ (hn _) (hn _),Option.bind_some] exact run_ratMinOne O _ (div_nonneg (hn _) (hn _)) open scoped Classical namespace Expression def memberPositions (w : Word) : List ℕ := (List.range w.length).filter (fun i => w[i]?.getD false) def membersCode : Expression .word (.list .nat) := both (wordLength >>> rangeCode) ident >>> filterWith (swap >>> wordGet) lemma run_membersCode {n : ℕ} (O : IndependenceOracle n) (w : Word) : run O membersCode w=some (memberPositions w) := by simp only [membersCode,run_compose,run_both,run_ident,run_wordLength,Option.bind_some,Option.map_some] rw [run_rangeCode] simp only [Option.bind_some] apply run_filterWith intro i w exact run_wordGet O w i lemma memberPositions_nodup (w : Word) : (memberPositions w).Nodup := List.nodup_range.filter _ end Expression lemma mem_memberPositions_source {n : ℕ} (S : Set (Fin n⊕Fin n)) (i : Fin n⊕Fin n) : position i∈Expression.memberPositions (combinedEncode S) ↔ i∈S := by simp only [Expression.memberPositions,List.mem_filter,List.mem_range,combinedEncode_length, combinedEncode_get,decide_eq_true_eq] exact and_iff_right (finSumFinEquiv i).isLt noncomputable def memberPositionEquiv {n : ℕ} (S : Set (Fin n⊕Fin n)) : {i : ℕ // i∈Expression.memberPositions (combinedEncode S)} ≃ S where toFun i := by have hi : i.val>> getDCode)) lemma uniformVia_size {A : Type*} [Fintype A] [Nonempty A] (m : ℕ) (e : Fin m ≃ A) (h : m=Fintype.card A) (hc : m-1+1=m) : (DrawTree.draw (m-1) (fun i => .leaf (e (Fin.cast hc i))))= DrawTree.uniformVia A ((finCongr h.symm).trans e) := by subst m rfl lemma realizes_uniformList {n : ℕ} (O : IndependenceOracle n) {A : Type*} [Fintype A] [Nonempty A] {a} (encode : A → Value a) (l : List (Value a)) (e : Fin l.length ≃ A) (he : ∀ i,l.get i=encode (e i)) : RealizesLaw O uniformList encode l (DrawTree.uniformChoice A) := by have hlen : l.length=Fintype.card A := by simpa using Fintype.card_congr e have hp : 0 .leaf (e (Fin.cast hc i))) have ht : t=DrawTree.uniformVia A ee := uniformVia_size l.length e hlen hc apply RealizesLaw.reindex (u:=t) · apply Realizes.law change Realizes O (letIn (precompose listLength draw) (pure _)) encode l ((DrawTree.draw (l.length-1) DrawTree.leaf).bind (fun i => .leaf (e (Fin.cast hc i)))) apply realizes_letIn O (a:=.list a) (b:=.nat) (c:=a) _ _ (fun i : Fin (l.length-1+1) => i.val) encode l _ _ · apply realizes_precompose O (a:=.list a) (b:=.nat) (c:=.nat) listLength draw (fun i : Fin (l.length-1+1) => i.val) l l.length _ (run_listLength O l) simpa only [hc] using realizes_draw O (l.length-1) · intro i apply realizes_pure simp only [run_compose,run_both,run_fst,run_snd,run_constant,Option.bind_some,Option.map_some] rw [run_getDCode] rw [List.getD_eq_getElem (l:=l) (d:=zeroValue a) (n:=i.val) (by omega)] exact congrArg some (he (Fin.cast hc i)) · rw [ht] exact (DrawTree.uniformVia_reindexed A ee).symm end Effect open scoped Classical open Expression lemma combinedEncode_compl {n : ℕ} (S : Set (Fin n⊕Fin n)) : combinedEncode Sᶜ=(combinedEncode S).map Bool.not := by simp [combinedEncode,stateEncode,List.map_append,List.map_ofFn,Function.comp_def] def exchangePositions (S : Word×Word) : List (ℕ×ℕ) := memberPositions (S.1++S.2) ×ˢ memberPositions ((S.1++S.2).map Bool.not) def Expression.exchangePositionsCode : Expression StateData (.list NN) := append >>> both membersCode (wordNot >>> membersCode) >>> productCode lemma run_exchangePositionsCode {n : ℕ} (O : IndependenceOracle n) (S : Word×Word) : run O exchangePositionsCode S=some (exchangePositions S) := by simp only [exchangePositionsCode,run_compose,run_both,run_append,Option.bind_some,run_membersCode, run_wordNot,Option.map_some] exact run_productCode O (a:=.nat) (b:=.nat) _ _ lemma exchangePositions_nodup (S : Word×Word) : (exchangePositions S).Nodup := by exact List.Nodup.product (memberPositions_nodup _) (memberPositions_nodup _) lemma memberPositionEquiv_val {n : ℕ} (S : Set (Fin n⊕Fin n)) (i : {i : ℕ // i∈memberPositions (combinedEncode S)}) : position (memberPositionEquiv S i).val=i.val := by simp [memberPositionEquiv,position] noncomputable def exchangePositionEquiv {n : ℕ} (S : Set (Fin n⊕Fin n)) : {p : ℕ×ℕ // p∈exchangePositions (stateEncode S)} ≃ ExchangeChoice S where toFun p := let hp : p.val∈memberPositions (combinedEncode S) ×ˢ memberPositions (combinedEncode Sᶜ) := by rw [combinedEncode_compl] exact p.property (memberPositionEquiv S ⟨p.val.1,(List.mem_product.mp hp).1⟩, memberPositionEquiv Sᶜ ⟨p.val.2,(List.mem_product.mp hp).2⟩) invFun p := ⟨(position p.1.val,position p.2.val),by change (position p.1.val, position p.2.val)∈ memberPositions (combinedEncode S) ×ˢ memberPositions ((combinedEncode S).map Bool.not) rw [←combinedEncode_compl] exact List.mem_product.mpr ⟨(mem_memberPositions_source S _).mpr p.1.property, (mem_memberPositions_source Sᶜ _).mpr p.2.property⟩⟩ left_inv p := by apply Subtype.ext; simp [memberPositionEquiv_val] right_inv p := by apply Prod.ext <;> apply Subtype.ext <;> simp [memberPositionEquiv,position] noncomputable def exchangeListEquiv {n : ℕ} (S : Set (Fin n⊕Fin n)) : Fin (exchangePositions (stateEncode S)).length ≃ ExchangeChoice S := (exchangePositions_nodup (stateEncode S)).getEquiv.trans (exchangePositionEquiv S) lemma exchangeListEquiv_val {n : ℕ} (S : Set (Fin n⊕Fin n)) (i : Fin (exchangePositions (stateEncode S)).length) : (position (exchangeListEquiv S i).1.val,position (exchangeListEquiv S i).2.val)= (exchangePositions (stateEncode S)).get i := by simp [exchangeListEquiv,exchangePositionEquiv,memberPositionEquiv_val,List.Nodup.getEquiv] namespace Effect def proposal : Effect StateData NN := precompose exchangePositionsCode uniformList lemma proposal_source {n : ℕ} (O : IndependenceOracle n) (S : Set (Fin n⊕Fin n)) [Nonempty (ExchangeChoice S)] : RealizesLaw O proposal (fun a : ExchangeChoice S => (position a.1.val,position a.2.val)) (stateEncode S) (DrawTree.uniformChoice (ExchangeChoice S)) := by apply law_precompose O _ _ _ _ _ _ (run_exchangePositionsCode O _) exact realizes_uniformList O _ _ (exchangeListEquiv S) (fun i => (exchangeListEquiv_val S i).symm) end Effect section open Expression open scoped Classical namespace Effect abbrev OfferInput := DataType.prod WeightInput StateData def acceptancePrep : Expression OfferInput AcceptanceInput := both (fst >>> fst) (both (fst >>> snd) snd) def offerCore : Effect OfferInput StateData := choose (snd >>> chainCode) (pure (fst >>> snd)) (letIn (precompose (acceptancePrep >>> acceptanceCode) bernoulliCode) (pure (applyIf snd (fst >>> fst >>> snd) (fst >>> snd)))) def offerCode : Effect (.prod WeightInput NN) StateData := precompose (both fst (both (fst >>> snd) snd >>> exchangeSetCode)) offerCore def activeStepCode : Effect WeightInput StateData := letIn (precompose snd proposal) offerCode def stepCode : Effect WeightInput StateData := letIn (precompose (constant (1,2)) bernoulliCode) (choose snd (precompose fst activeStepCode) (pure (fst >>> snd))) end Effect variable {n : ℕ} (M₁ M₂ : Matroid (Fin n)) (O : IndependenceOracle n) (hO : ExactOracles M₁ M₂ O) (hE₁ : M₁.E=Set.univ) (hE₂ : M₂.E=Set.univ) (r j : ℕ) (h : List (List (Set (Fin n⊕Fin n)))) local notation "GS" => pairedSlots n local notation "ctx" => (((r,j),historyEncode h) : Value WeightContext) local notation "W" => rationalHistory GS id h local notation "F" => oracleAnneal n r O j open Effect include M₁ M₂ hO hE₁ hE₂ lemma offerCore_source (S : ChainIndex GS) (U : Set (Fin n⊕Fin n)) : RealizesLaw O offerCore (fun T : ChainIndex GS => stateEncode T.val) ((ctx,stateEncode S.val),stateEncode U) (if hu : ChainState GS U then (DrawTree.bernoulli (rationalAcceptance GS W F S ⟨U,hu⟩)).map (fun b => if b then ⟨U,hu⟩ else S) else .leaf S) := by have ht : run O ((snd (a:=WeightInput) (b:=StateData)) >>> chainCode) ((ctx,stateEncode S.val),stateEncode U)=some (decide (ChainState GS U)) := by change run O chainCode (stateEncode U)=_ rw [run_chainCode,chainValue_source] unfold offerCore apply law_choose O _ _ _ _ _ _ _ ht by_cases hu : ChainState GS U · simp only [hu,decide_true,ite_true,dite_eq_left] change RealizesLaw O (letIn (precompose _ bernoulliCode) (pure _)) _ _ ((DrawTree.bernoulli (rationalAcceptance GS W F S ⟨U,hu⟩)).bind (fun b => .leaf (if b then ⟨U,hu⟩ else S))) apply law_letIn O (a:=OfferInput) (b:=.bool) (c:=StateData) _ _ id _ _ _ _ · apply Realizes.law apply realizes_precompose O _ _ _ _ (rationalPair (rationalAcceptance GS W F S ⟨U,hu⟩)) · exact acceptanceCode_source M₁ M₂ O hO hE₁ hE₂ r j h S ⟨U,hu⟩ · exact bernoulliCode_source O _ · intro b apply Realizes.law apply realizes_pure cases b <;> rfl · simp only [hu,decide_false,Bool.false_eq_true,ite_false] exact (realizes_pure O _ _ _ S rfl).law lemma offerCode_source (S : ChainIndex GS) (a : ExchangeChoice S.val) : RealizesLaw O offerCode (fun T : ChainIndex GS => stateEncode T.val) ((ctx,stateEncode S.val),(position a.1.val,position a.2.val)) (rationalExchange GS W F S a) := by unfold offerCode apply law_precompose O _ _ _ _ ((ctx,stateEncode S.val),stateEncode (exchangedSet S.val a)) · simp only [run_both,run_compose,run_fst,run_snd,Option.bind_some,Option.map_some] rw [exchangeSetCode_source] rfl · exact offerCore_source M₁ M₂ O hO hE₁ hE₂ r j h S _ lemma activeStepCode_source (S : ChainIndex GS) [Nonempty (ExchangeChoice S.val)] : RealizesLaw O activeStepCode (fun T : ChainIndex GS => stateEncode T.val) (ctx,stateEncode S.val) ((DrawTree.uniformChoice (ExchangeChoice S.val)).bind (rationalExchange GS W F S)) := by unfold activeStepCode apply law_letIn O (a:=WeightInput) (b:=NN) (c:=StateData) _ _ (fun a : ExchangeChoice S.val => (position a.1.val,position a.2.val)) _ _ _ _ · exact law_precompose O snd proposal _ _ _ _ rfl (proposal_source O S.val) · exact offerCode_source M₁ M₂ O hO hE₁ hE₂ r j h S lemma stepCode_source (hn : 0 stateEncode T.val) (ctx,stateEncode S.val) (rationalMetropolis GS (pairedSlots_fresh n) (pairedSlots_ne_nil n hn) (pairedSlots_cover n) W F S) := by let : Nonempty (ExchangeChoice S.val) := Fintype.card_pos_iff.mp (by rw [exchangeChoice_card GS (pairedSlots_fresh n) (pairedSlots_cover n),pairedSlots_length]; positivity) unfold stepCode rationalMetropolis apply law_letIn O (a:=WeightInput) (b:=.bool) (c:=StateData) _ _ id _ _ _ _ · apply Realizes.law exact realizes_precompose O _ bernoulliCode id _ (rationalPair (1/2)) _ (by norm_num [run_constant,rationalPair]) (bernoulliCode_source O _) · intro b apply law_choose O _ _ _ _ _ _ b rfl cases b with | false => exact law_precompose O fst activeStepCode _ _ _ _ rfl (activeStepCode_source M₁ M₂ O hO hE₁ hE₂ r j h S) | true => exact (realizes_pure O _ _ _ S rfl).law end section open Expression open scoped Classical lemma binaryValue_injective_length (x y : Word) (hlen : x.length=y.length) (hv : binaryValue x=binaryValue y) : x=y := by induction x generalizing y with | nil => cases y <;> simp_all | cons b x ih => cases y with | nil => simp at hlen | cons c y => simp only [List.length_cons,Nat.add_right_cancel_iff] at hlen have hbc : b=c := by cases b <;> cases c <;> simp_all [binaryValue] <;> omega subst c have hxy : binaryValue x=binaryValue y := by cases b <;> simp_all [binaryValue] rw [ih y hlen hxy] lemma binaryValue_replicate_false (k : ℕ) : binaryValue (List.replicate k false)=0 := by induction k with | zero => rfl | succ k ih => simp [List.replicate_succ,binaryValue,ih] lemma padded_range (w : Word) (k : ℕ) (hk : w.length≤k) : (List.range k).map (fun i => w[i]?.getD false)=w++List.replicate (k-w.length) false := by apply List.ext_getElem · simp; omega · intro i hi hj simp only [List.getElem_map,List.getElem_range] by_cases h : i>> rangeCode) (snd >>> toBits) >>> mapWith (swap >>> wordGet) >>> fromList >>> reverse lemma run_paddedBitsCode {n : ℕ} (O : IndependenceOracle n) (k v : ℕ) (hv : v<2^k) : run O paddedBitsCode (k,v)=some (List.ofFn ((wordEquiv k).symm ⟨v,hv⟩)) := by have hk : v.bits.length≤k := by rw [Nat.size_eq_bits_len]; exact Nat.size_le.mpr hv have hr : (List.range k).map (fun i => v.bits[i]?.getD false)=v.bits++List.replicate (k-v.bits.length) false := padded_range _ _ hk have he : ((List.range k).map (fun i => v.bits[i]?.getD false)).reverse= List.ofFn ((wordEquiv k).symm ⟨v,hv⟩) := by apply List.reverse_inj.mp simp only [List.reverse_reverse] apply binaryValue_injective_length · simp · rw [hr,binaryValue_append,binaryValue_replicate_false,binaryValue_bits,binaryValue_ofFn_reverse] simp simp only [paddedBitsCode,run_compose,run_both,run_fst,run_snd,Option.bind_some] rw [run_rangeCode] change ((run O (mapWith (c:=.word) (Expression.swap >>> wordGet)) (List.range k,v.bits)).bind fun l => (run O fromList l).bind (run O reverse))=_ rw [run_mapWith O (c:=.word) (Expression.swap >>> wordGet) (fun i w => w[i]?.getD false) (fun i w => run_wordGet O w i)] simp only [Option.bind_some] rw [run_fromList] exact congrArg some he def plainDecodeCode : Expression NN StateData := paddedBitsCode >>> both ident wordNot lemma plainDecodeCode_source {n : ℕ} (O : IndependenceOracle n) (v : Fin (2^n)) : run O plainDecodeCode (n,v.val)=some (stateEncode (wordPlainEquiv n ((wordEquiv n).symm v)).val.val) := by rw [plainDecodeCode,run_compose,run_paddedBitsCode O n v.val v.isLt,Option.bind_some,run_both,run_ident,Option.bind_some,run_wordNot] simp only [Option.map_some] congr 1 change (List.ofFn _,(List.ofFn _).map Bool.not)=_ unfold stateEncode wordPlainEquiv simp only [] apply Prod.ext · apply List.ext_getElem <;> simp [transversal] · apply List.ext_getElem <;> simp [transversal] end Expression namespace Effect noncomputable local instance {n : ℕ} : Nonempty (PlainIndex (pairedSlots n)) := plainIndex_nonempty _ (pairedSlots_fresh n) (pairedSlots_cover n) def plainCode : Effect .nat StateData := letIn (precompose (both (constant 2) ident >>> powCode) draw) (pure plainDecodeCode) lemma plainCode_source {n : ℕ} (O : IndependenceOracle n) : RealizesLaw O plainCode (fun S : PlainIndex (pairedSlots n) => stateEncode S.val.val) n (DrawTree.uniformVia _ (canonicalPlainEnumeration n)) := by have hp : 0<2^n := by positivity let hc : 2^n-1+1=2^n := by omega let e : Fin (2^n) ≃ PlainIndex (pairedSlots n) := (wordEquiv n).symm.trans (wordPlainEquiv n) let t : DrawTree (PlainIndex (pairedSlots n)) := .draw (2^n-1) (fun i => .leaf (e (Fin.cast hc i))) have ht : t=DrawTree.uniformVia _ (canonicalPlainEnumeration n) := by exact uniformVia_size (2^n) e (plainIndex_card n).symm hc rw [←ht] apply Realizes.law change Realizes O (letIn (a:=.nat) (b:=.nat) (c:=StateData) _ _) _ n ((DrawTree.draw (2^n-1) DrawTree.leaf).bind (fun i => .leaf (e (Fin.cast hc i)))) apply realizes_letIn O (a:=.nat) (b:=.nat) (c:=StateData) _ _ (fun i : Fin (2^n-1+1) => i.val) _ n _ _ · apply realizes_precompose O _ draw _ _ (2^n) · change run O powCode (2,n)=_; exact run_powCode O 2 n · simpa only [hc] using realizes_draw O (2^n-1) · intro i apply realizes_pure exact plainDecodeCode_source O (Fin.cast hc i) def storedStepPrep : Expression WeightInput WeightInput := both (both (fst >>> fst) (both (fst >>> snd) (fst >>> fst >>> snd) >>> takeCode)) snd def storedStepCode : Effect WeightInput StateData := precompose storedStepPrep stepCode def traceCode : Effect (.prod .nat WeightInput) (Optional StateData) := map (hittingCode (withContext storedStepCode) (snd >>> Expression.plainCode)) (optionMapCode snd) end Effect lemma rationalHistory_map {X : Type*} {n : ℕ} (f : X → List (Set (Fin n⊕Fin n))) (h : List X) : rationalHistory (pairedSlots n) id (h.map f)=rationalHistory (pairedSlots n) f h := by simp only [rationalHistory,List.foldl_map,id_eq] lemma historyEncode_take {n : ℕ} (h : List (List (Set (Fin n⊕Fin n)))) (j : ℕ) : (historyEncode h).take j=historyEncode (h.take j) := by simp only [historyEncode,List.map_take] variable {n : ℕ} (M₁ M₂ : Matroid (Fin n)) (O : IndependenceOracle n) (hO : ExactOracles M₁ M₂ O) (hE₁ : M₁.E=Set.univ) (hE₂ : M₂.E=Set.univ) (r N : ℕ) (h : List (PhaseSample n N)) (j : ℕ) (hn : 0 pairedSlots n local notation "ctx" => (((r,j),historyEncode (h.map (observedSets n N))) : Value WeightContext) open Effect include M₁ M₂ hO hE₁ hE₂ lemma storedStepCode_source (S : ChainIndex GS) : RealizesLaw O storedStepCode (fun T : ChainIndex GS => stateEncode T.val) (ctx,stateEncode S.val) (canonicalStepTree n hn r O N h j S) := by unfold storedStepCode apply law_precompose O storedStepPrep stepCode _ _ (((r,j),historyEncode ((h.map (observedSets n N)).take j)),stateEncode S.val) · simp only [storedStepPrep,run_both,run_compose,run_fst,run_snd,Option.bind_some,Option.map_some] rw [run_takeCode,historyEncode_take]; rfl · have hp := stepCode_source M₁ M₂ O hO hE₁ hE₂ r j ((h.map (observedSets n N)).take j) hn S have he : rationalHistory GS id ((h.map (observedSets n N)).take j)=rationalStored n N h j := by rw [←List.map_take,rationalHistory_map]; rfl rw [he] at hp exact hp.reindex (canonicalMetropolis_reindexed n hn _ _ S) lemma traceCode_source (cap : ℕ) (S : PlainIndex GS) : RealizesLaw O traceCode (optionEncode (fun T : PlainIndex GS => stateEncode T.val.val)) (cap+1,(ctx,stateEncode S.val.val)) (canonicalTraceTree n hn r O N h j cap S) := by unfold traceCode canonicalTraceTree apply law_optionRecode O _ snd (fun y : PlainIndex GS => (ctx,stateEncode y.val.val)) _ _ _ · exact law_hitting O (withContext storedStepCode) (snd >>> Expression.plainCode) (fun T : ChainIndex GS => (ctx,stateEncode T.val)) (canonicalStepTree n hn r O N h j) (plainPredicate GS) (fun T => law_withContext O storedStepCode _ ctx _ _ (storedStepCode_source M₁ M₂ O hO hE₁ hE₂ r N h j hn T)) (fun T => plainCode_source O T.val) (cap+1) S.val · intro T; rfl end section open Expression namespace Effect def withOptionContext {a b c} (p : Effect (.prod c a) (Optional b)) : Effect (.prod c a) (Optional (.prod c b)) := letIn p (pure (applyIf (snd >>> fst) (constant (optionalValue (.prod c b) none)) (both (constant true) (both (fst >>> fst) (snd >>> snd))))) lemma law_withOptionContext {n : ℕ} (O : IndependenceOracle n) {A : Type*} {a b c} (p : Effect (.prod c a) (Optional b)) (e : A → Value b) (ctx : Value c) (x : Value a) (t : DrawTree (Option A)) (hp : RealizesLaw O p (optionEncode e) (ctx,x) t) : RealizesLaw O (withOptionContext p) (optionEncode (fun y => (ctx,e y))) (ctx,x) t := by unfold withOptionContext rw [←DrawTree.bind_leaf t] apply law_letIn O p _ (optionEncode e) _ _ t DrawTree.leaf hp intro y apply Realizes.law apply realizes_pure cases y <;> rfl end Effect open Expression open scoped Classical abbrev RestartContext : DataType := .prod (.prod .nat HistoryData) (.prod .nat .nat) abbrev RestartState : DataType := .prod (.prod RestartContext .nat) StateData abbrev RestartInput : DataType := .prod .nat (.prod .nat RestartContext) namespace Effect def traceAtPrep : Expression RestartState (.prod .nat WeightInput) := both (fst >>> fst >>> snd >>> fst >>> (both ident (constant 1) >>> add)) (both (both (both (fst >>> fst >>> fst >>> fst) (fst >>> snd)) (fst >>> fst >>> fst >>> snd)) snd) def traceAtCode : Effect RestartState (Optional StateData) := precompose traceAtPrep traceCode def restartTickPrep : Expression RestartState (.prod .nat RestartState) := both (fst >>> fst >>> snd >>> snd) (both (both (fst >>> fst) (fst >>> snd >>> (both ident (constant 1) >>> add))) snd) def restartTick : Effect RestartState (Optional RestartState) := precompose restartTickPrep (iterateCode (withOptionContext traceAtCode)) def restartPrep : Expression (.prod RestartInput StateData) (.prod .nat (Optional RestartState)) := both (fst >>> snd >>> fst) (both (constant true) (both (both (fst >>> snd >>> snd) (constant 0)) snd)) def restartCode : Effect RestartInput (Optional StateData) := map (letIn (precompose fst plainCode) (precompose restartPrep (repeatCode (optionContinue restartTick)))) (optionMapCode snd) end Effect section Correct variable {n : ℕ} (M₁ M₂ : Matroid (Fin n)) (O : IndependenceOracle n) (hO : ExactOracles M₁ M₂ O) (hE₁ : M₁.E=Set.univ) (hE₂ : M₂.E=Set.univ) (r N L : ℕ) (h : List (PhaseSample n N)) (hn : 0 pairedSlots n local notation "tau" => 20*n^4*(n*(L+1)+2) local notation "ctx" => (((r,historyEncode (h.map (observedSets n N))),(cap,tau)) : Value RestartContext) local notation "enc" => (fun j (x : PlainIndex GS) => ((ctx,j),stateEncode (Subtype.val (Subtype.val x)))) open Effect include M₁ M₂ hO hE₁ hE₂ lemma traceAtCode_source (j : ℕ) (x : PlainIndex GS) : RealizesLaw O traceAtCode (optionEncode (fun y : PlainIndex GS => stateEncode y.val.val)) (enc j x) (canonicalTraceTree n hn r O N h j cap x) := by apply law_precompose O traceAtPrep traceCode _ _ _ _ · rfl · exact traceCode_source M₁ M₂ O hO hE₁ hE₂ r N h j hn cap x lemma restartTick_source (j : ℕ) (x : PlainIndex GS) : RealizesLaw O restartTick (optionEncode (enc (j+1))) (enc j x) (DrawTree.iterate (canonicalTraceTree n hn r O N h (j+1) cap) tau x) := by apply law_precompose O restartTickPrep _ _ _ _ _ · rfl · apply law_iterate O (withOptionContext traceAtCode) (enc (j+1)) _ _ tau x intro y apply law_withOptionContext exact traceAtCode_source M₁ M₂ O hO hE₁ hE₂ r N L h hn cap (j+1) y end Correct open Effect lemma canonicalRestart_phaseRepeat {n : ℕ} (hn : 0 phaseRepeat (fun j => DrawTree.iterate (canonicalTraceTree n hn r O N h j cap) (20*n^4*(n*(L+1)+2))) k x)) := by let := plainIndex_nonempty (pairedSlots n) (pairedSlots_fresh n) (pairedSlots_cover n) induction k with | zero => rfl | succ k ih => rw [canonicalRestartTree,ih,Effect.phaseRepeat_bind] variable {n : ℕ} (M₁ M₂ : Matroid (Fin n)) (O : IndependenceOracle n) (hO : ExactOracles M₁ M₂ O) (hE₁ : M₁.E=Set.univ) (hE₂ : M₂.E=Set.univ) (r N L : ℕ) (h : List (PhaseSample n N)) (hn : 0 pairedSlots n local notation "tau" => 20*n^4*(n*(L+1)+2) local notation "ctx" => (((r,historyEncode (h.map (observedSets n N))),(cap,tau)) : Value RestartContext) local notation "enc" => (fun j (x : PlainIndex GS) => ((ctx,j),stateEncode (Subtype.val (Subtype.val x)))) open Effect include M₁ M₂ hO hE₁ hE₂ lemma restartCode_source : RealizesLaw O restartCode (optionEncode (fun x : PlainIndex GS => stateEncode x.val.val)) (n,(k,ctx)) (canonicalRestartTree n hn r O N L h cap k) := by rw [canonicalRestart_phaseRepeat] unfold restartCode apply law_optionRecode O _ snd (enc k) _ _ _ · apply law_letIn O _ _ (fun x : PlainIndex GS => stateEncode x.val.val) _ _ _ _ · exact law_precompose O fst plainCode _ _ n _ rfl (Effect.plainCode_source O) · intro x apply law_precompose O restartPrep _ _ _ _ _ · rfl · exact law_phaseRepeat O restartTick enc _ (restartTick_source M₁ M₂ O hO hE₁ hE₂ r N L h hn cap) k x · intro x; rfl end open Expression open scoped Classical namespace Expression def allRange {a} (p : Expression (.prod .nat a) .bool) : Expression (.prod .nat a) .bool := both (fst >>> rangeCode) snd >>> mapWith p >>> listAll lemma run_allRange {n : ℕ} (O : IndependenceOracle n) {a} (p : Expression (.prod .nat a) .bool) (f : ℕ → Value a → Bool) (hp : ∀ i x,run O p (i,x)=some (f i x)) (m : ℕ) (x : Value a) : run O (allRange p) (m,x)=some (decide (∀ i < m,f i x=true)) := by simp only [allRange,run_compose,run_both,run_fst,run_snd,Option.bind_some,Option.map_some] rw [run_rangeCode] simp only [Option.bind_some,run_compose] rw [run_mapWith O p f hp,Option.bind_some,run_listAll] congr 1 apply Bool.eq_iff_iff.mpr simp end Expression lemma rationalPair_pos {q : ℚ} (hq : 0 ≤ q) : 0 < (rationalPair q).1 ↔ 0 < q := by have hd : (0:ℚ) < (rationalPair q).2 := by exact_mod_cast rationalPair_den q conv_rhs => rw [←rationalPair_value hq] rw [div_pos_iff_of_pos_right hd] exact_mod_cast (Iff.rfl : 0 < (rationalPair q).1 ↔ 0 < (rationalPair q).1) namespace Expression def pairPositiveCode : Expression (.prod HistoryData NN) .bool := historyWeightCode >>> fst >>> natEqZero >>> boolNot lemma run_pairPositiveCode {n : ℕ} (O : IndependenceOracle n) (h : List (List (Word×Word))) (p q : ℕ) : run O pairPositiveCode (h,(p,q))=some (decide (0 < historyWeightValue p q h)) := by simp only [pairPositiveCode,run_compose] rw [run_historyWeightCode] simp only [Option.bind_some,run_compose,run_fst] rw [run_natEqZero] simp only [Option.bind_some,run_boolNot] congr 1 apply Bool.eq_iff_iff.mpr simp only [Bool.not_eq_true',decide_eq_false_iff_not,decide_eq_true_eq] exact (Nat.pos_iff_ne_zero.symm).trans (rationalPair_pos (historyWeightValue_nonneg p q h)) def slotRowCode : Expression (.prod .nat (.prod .nat HistoryData)) .bool := both (snd >>> fst) (both fst (snd >>> snd)) >>> allRange (both (snd >>> snd) (both (snd >>> fst) fst) >>> pairPositiveCode) def slotsPositiveCode : Expression (.prod .nat HistoryData) .bool := both fst ident >>> allRange slotRowCode def prefixPositiveCode : Expression (.prod .nat (.prod .nat HistoryData)) .bool := both (snd >>> fst) (both (snd >>> snd) fst >>> takeCode) >>> slotsPositiveCode def historyPositiveCode : Expression (.prod .nat HistoryData) .bool := both (snd >>> listLength >>> (both ident (constant 1) >>> add)) ident >>> allRange prefixPositiveCode lemma run_slotRowCode {n : ℕ} (O : IndependenceOracle n) (p m : ℕ) (h : List (List (Word×Word))) : run O slotRowCode (p,(m,h))=some (decide (∀ q < m,0 < historyWeightValue p q h)) := by change run O (allRange (a:=.prod .nat HistoryData) _) (m,(p,h))=_ rw [run_allRange (a:=.prod .nat HistoryData) O _ (fun q u => decide (0 < historyWeightValue u.1 q u.2))] · simp · intro q u; exact run_pairPositiveCode O u.2 u.1 q lemma run_slotsPositiveCode {n : ℕ} (O : IndependenceOracle n) (m : ℕ) (h : List (List (Word×Word))) : run O slotsPositiveCode (m,h)=some (decide (∀ p < m,∀ q < m,0 < historyWeightValue p q h)) := by change run O (allRange slotRowCode) (m,(m,h))=_ rw [run_allRange (a:=.prod .nat HistoryData) O _ (fun p u => decide (∀ q < u.1,0 < historyWeightValue p q u.2)) (fun p u => run_slotRowCode O p u.1 u.2)] simp lemma run_prefixPositiveCode {n : ℕ} (O : IndependenceOracle n) (j m : ℕ) (h : List (List (Word×Word))) : run O prefixPositiveCode (j,(m,h))=some (decide (∀ p < m,∀ q < m,0 < historyWeightValue p q (h.take j))) := by simp only [prefixPositiveCode,run_compose,run_both,run_fst,run_snd,Option.bind_some,Option.map_some] rw [run_takeCode] exact run_slotsPositiveCode O m (h.take j) lemma run_historyPositiveCode {n : ℕ} (O : IndependenceOracle n) (m : ℕ) (h : List (List (Word×Word))) : run O historyPositiveCode (m,h)=some (decide (∀ j ≤ h.length,∀ p < m,∀ q < m,0 < historyWeightValue p q (h.take j))) := by simp only [historyPositiveCode,run_compose,run_both,run_snd,run_ident,run_constant,Option.bind_some,Option.map_some] rw [run_listLength] change run O (allRange prefixPositiveCode) (h.length+1,(m,h))=_ rw [run_allRange (a:=.prod .nat HistoryData) O _ (fun j u => decide (∀ p < u.1,∀ q < u.1,0 < historyWeightValue p q (u.2.take j))) (fun j u => run_prefixPositiveCode O j u.1 u.2)] simp only [decide_eq_true_eq,Nat.lt_add_one_iff] end Expression lemma rationalHistory_inactive {Γ X : Type*} [DecidableEq Γ] (gs : List (Γ×Γ)) (s : X → List (Set Γ)) (h : List X) (p q : Γ×Γ) (hp : ¬(p∈gs ∧ q∈gs ∧ p≠q)) : rationalHistory gs s h p q=4 := by have hh : ∀ (l : List X) (w : (Γ×Γ) → (Γ×Γ) → ℚ), (l.foldl (fun w x => rationalLearn gs w (s x)) w) p q=w p q := by intro l induction l with | nil => intro w; rfl | cons x l ih => intro w; rw [List.foldl_cons,ih]; simp [rationalLearn,hp] exact hh h _ lemma rationalHistoryPositive_slots {n N : ℕ} (h : List (PhaseSample n N)) : rationalHistoryPositive n N h ↔ ∀ j ≤ h.length,∀ p q : Fin n,0 < rationalStored n N h j (slotPair p) (slotPair q) := by constructor · intro hh j hj p q; exact hh j hj _ _ · intro hh j hj p q by_cases hpq : p∈pairedSlots n ∧ q∈pairedSlots n ∧ p≠q · obtain ⟨a,ha,rfl⟩ := List.mem_map.mp hpq.1 obtain ⟨b,hb,rfl⟩ := List.mem_map.mp hpq.2.1 exact hh j hj a b · change 0 < rationalHistory _ _ _ p q have hz := rationalHistory_inactive (pairedSlots n) (observedSets n N) (h.take j) p q hpq rw [hz]; norm_num lemma historyPositiveCode_source {n N : ℕ} (O : IndependenceOracle n) (h : List (PhaseSample n N)) : run O Expression.historyPositiveCode (n,historyEncode (h.map (observedSets n N)))= some (decide (rationalHistoryPositive n N h)) := by rw [Expression.run_historyPositiveCode] congr 1 apply Bool.eq_iff_iff.mpr simp only [decide_eq_true_eq] rw [rationalHistoryPositive_slots] have hlen : (historyEncode (h.map (observedSets n N))).length=h.length := by simp [historyEncode] rw [hlen] constructor · intro hp j hj p q have hh := hp j hj p.val p.isLt q.val q.isLt rw [historyEncode_take,historyWeight_source,←List.map_take,rationalHistory_map] at hh exact hh · intro hp j hj p hp' q hq' rw [historyEncode_take,historyWeight_source (p:=⟨p,hp'⟩) (r:=⟨q,hq'⟩),←List.map_take,rationalHistory_map] exact hp j hj ⟨p,hp'⟩ ⟨q,hq'⟩ end MachineCode namespace DrawTree lemma Reindexed.lift_map {A B : Type*} (f : A → B) (t : DrawTree A) (u : DrawTree B) (h : Reindexed (t.map f) u) : ∃ v, Reindexed t v ∧ v.map f=u := by classical induction t generalizing u with | leaf a => cases h exact ⟨.leaf a,.leaf a,rfl⟩ | draw w k ih => cases h with | draw _ _ l e hh => choose v hv he using fun i => ih i (l (e i)) (hh i) refine ⟨.draw w (fun i => v (e.symm i)),.draw w k _ e (by intro i; simpa using hv i),?_⟩ simp only [DrawTree.map,DrawTree.bind] at he ⊢ congr 1 funext i simpa using he (e.symm i) end DrawTree namespace MachineCode open Expression namespace Effect lemma law_unmap {n : ℕ} (O : IndependenceOracle n) {A B : Type*} {a b} (p : Effect a b) (e : B → Value b) (x : Value a) (t : DrawTree A) (f : A → B) (h : RealizesLaw O p e x (t.map f)) : RealizesLaw O p (e ∘ f) x t := by rcases h with ⟨u,hu,hp⟩ obtain ⟨v,hv,rfl⟩ := hu.lift_map f t u refine ⟨v,hv,fun bank => ?_⟩ simpa only [bankEval_map,Option.map_map,Function.comp_def] using hp bank def sampleTick {a} (p : Effect a a) : Effect (.prod (.list a) a) (.prod (.list a) a) := letIn (precompose snd p) (pure (both (both (fst >>> snd) (fst >>> fst) >>> cons) snd)) def sampleFinish {a} : Expression (.prod (.list a) a) (.list a) := both (fst >>> listReverse) (both snd (constant []) >>> cons) >>> listAppend def sampleCode {a} (p : Effect a a) : Effect (.prod .nat a) (.list a) := precompose (both fst (both (constant []) snd)) (map (repeatCode (sampleTick p)) sampleFinish) def sampleTickTree {X : Type*} (f : X → DrawTree X) (s : List X × X) : DrawTree (List X × X) := (f s.2).map (fun y => (s.2::s.1,y)) lemma sampleRepeat_finish {X : Type*} (f : X → DrawTree X) (k : ℕ) (acc : List X) (x : X) : (treeRepeat (sampleTickTree f) k (acc,x)).map (fun s => s.1.reverse++[s.2])= (DrawTree.sample f k x).map (fun v => acc.reverse++v.toList) := by induction k generalizing acc x with | zero => rfl | succ k ih => simp only [treeRepeat,sampleTickTree,DrawTree.map_bind,DrawTree.bind_map,DrawTree.sample] congr 1 funext y rw [ih] change (DrawTree.sample f k y).map (fun v => (x::acc).reverse++v.toList)= ((DrawTree.sample f k y).map (fun v => (x,v))).map (fun v : X × FiniteChain.Sample X k => acc.reverse++v.1::v.2.toList) rw [DrawTree.map_map] congr 1 funext v simp [List.reverse_cons,List.append_assoc] lemma law_sampleTick {n : ℕ} (O : IndependenceOracle n) {X : Type*} {a} (p : Effect a a) (e : X → Value a) (f : X → DrawTree X) (hp : ∀ x,RealizesLaw O p e (e x) (f x)) (s : List X × X) : RealizesLaw O (sampleTick p) (fun u => (u.1.map e,e u.2)) (s.1.map e,e s.2) (sampleTickTree f s) := by unfold sampleTick sampleTickTree DrawTree.map apply law_letIn O (a:=.prod (.list a) a) (b:=a) (c:=.prod (.list a) a) _ _ e _ _ _ _ · exact law_precompose O snd p _ _ _ _ rfl (hp s.2) · intro y exact (realizes_pure O _ _ _ (s.2::s.1,y) rfl).law lemma law_sample {n : ℕ} (O : IndependenceOracle n) {X : Type*} {a} (p : Effect a a) (e : X → Value a) (f : X → DrawTree X) (hp : ∀ x,RealizesLaw O p e (e x) (f x)) (k : ℕ) (x : X) : RealizesLaw O (sampleCode p) (fun v => v.toList.map e) (k,e x) (DrawTree.sample f k x) := by apply law_unmap O (a:=.prod .nat a) (b:=.list a) (sampleCode p) (fun l : List X => l.map e) (k,e x) (DrawTree.sample f k x) (fun v => v.toList) unfold sampleCode apply law_precompose O _ _ _ _ (k,(([] : List (Value a)),e x)) _ rfl have he := sampleRepeat_finish f k [] x simp only [List.reverse_nil,List.nil_append] at he rw [←he] apply law_map O _ _ (fun u : List X × X => (u.1.map e,e u.2)) _ _ _ _ · exact law_repeat O (sampleTick p) _ _ (law_sampleTick O p e f hp) k ([],x) · intro u simp only [sampleFinish,run_compose,run_both,run_fst,run_snd,run_constant,Option.bind_some,Option.map_some] rw [run_listReverse] change run O listAppend ((u.1.map e).reverse,[e u.2])=_ rw [run_listAppend] simp end Effect section open Expression open scoped Classical abbrev AlgorithmParams : DataType := .prod NN (.prod NN NN) abbrev PhaseInput : DataType := .prod AlgorithmParams HistoryData def params (n r N L : ℕ) : Value AlgorithmParams := ((n,r),((N,L),(restartCap n L,20*n^4*(n*(L+1)+2)))) namespace Expression def mapEach {a b} (p : Expression a b) : Expression (.list a) (.list b) := both ident (constant (b:=.unit) ()) >>> mapWith (fst >>> p) lemma run_mapEach {n : ℕ} (O : IndependenceOracle n) {a b} (p : Expression a b) (f : Value a → Value b) (hp : ∀ x,run O p x=some (f x)) (xs : List (Value a)) : run O (mapEach p) xs=some (xs.map f) := by change run O (mapWith (c:=.unit) (fst >>> p)) (xs,())=_ exact run_mapWith (c:=.unit) O _ (fun x _ => f x) (fun x _ => hp x) xs () end Expression namespace Effect def retainOption {a b} (p : Effect a (Optional b)) : Effect a (Optional (.prod a b)) := letIn p (pure (applyIf (snd >>> fst) (constant (optionalValue (.prod a b) none)) (both (constant true) (both fst (snd >>> snd))))) lemma law_retainOption {n : ℕ} (O : IndependenceOracle n) {A : Type*} {a b} (p : Effect a (Optional b)) (e : A → Value b) (x : Value a) (t : DrawTree (Option A)) (hp : RealizesLaw O p (optionEncode e) x t) : RealizesLaw O (retainOption p) (optionEncode (fun y => (x,e y))) x t := by unfold retainOption rw [←DrawTree.bind_leaf t] apply law_letIn O p _ (optionEncode e) _ _ t DrawTree.leaf hp intro y apply Realizes.law apply realizes_pure cases y <;> rfl def phaseRestartPrep : Expression PhaseInput RestartInput := both (fst >>> fst >>> fst) (both (snd >>> listLength) (both (both (fst >>> fst >>> snd) snd) (fst >>> snd >>> snd))) def phaseRestartCode : Effect PhaseInput (Optional StateData) := precompose phaseRestartPrep restartCode def startCode : Effect PhaseInput (Optional StateData) := map phaseRestartCode (optionMapCode ident) def phaseStepPrep : Expression (.prod PhaseInput StateData) WeightInput := both (both (both (fst >>> fst >>> fst >>> snd) (fst >>> snd >>> listLength)) (fst >>> snd)) snd def phaseStepCode : Effect (.prod PhaseInput StateData) StateData := precompose phaseStepPrep storedStepCode def phaseSamplePrep : Expression (.prod PhaseInput StateData) (.prod .nat (.prod PhaseInput StateData)) := both (both (fst >>> fst >>> snd >>> fst >>> fst) (constant 1) >>> natSub) ident def phaseSampleCode : Effect (.prod PhaseInput StateData) SampleData := precompose phaseSamplePrep (map (sampleCode (withContext phaseStepCode)) (mapEach snd)) def positiveTest : Expression PhaseInput .bool := both (fst >>> fst >>> fst) snd >>> historyPositiveCode def phaseCode : Effect PhaseInput (Optional SampleData) := choose positiveTest noneCode (optionBind (retainOption startCode) (someCode phaseSampleCode)) def witnessCode : Effect PhaseInput (Optional StateData) := choose positiveTest noneCode phaseRestartCode end Effect variable {n : ℕ} (M₁ M₂ : Matroid (Fin n)) (O : IndependenceOracle n) (hO : ExactOracles M₁ M₂ O) (hE₁ : M₁.E=Set.univ) (hE₂ : M₂.E=Set.univ) (r N L : ℕ) (h : List (PhaseSample n N)) (hn : 0 pairedSlots n local notation "ctx" => ((params n r N L,historyEncode (h.map (observedSets n N))) : Value PhaseInput) open Effect include M₁ M₂ hO hE₁ hE₂ lemma phaseRestartCode_source : RealizesLaw O phaseRestartCode (optionEncode (fun x : PlainIndex GS => stateEncode x.val.val)) ctx (canonicalRestartTree n hn r O N L h (restartCap n L) h.length) := by apply law_precompose O phaseRestartPrep restartCode _ ctx _ _ · simp only [phaseRestartPrep,params,run_both,run_compose,run_fst,run_snd,Option.bind_some,Option.map_some] rw [run_listLength] simp only [historyEncode,List.length_map] rfl · exact restartCode_source M₁ M₂ O hO hE₁ hE₂ r N L h hn _ _ lemma startCode_source : RealizesLaw O startCode (optionEncode (fun x : ChainIndex GS => stateEncode x.val)) ctx (canonicalStartTree n hn r O N L h) := by apply law_optionMap O phaseRestartCode ident (fun x : PlainIndex GS => stateEncode x.val.val) _ ctx _ Subtype.val · exact phaseRestartCode_source M₁ M₂ O hO hE₁ hE₂ r N L h hn · intro x; rfl lemma phaseStepCode_source (x : ChainIndex GS) : RealizesLaw O phaseStepCode (fun y : ChainIndex GS => stateEncode y.val) (ctx,stateEncode x.val) (canonicalStepTree n hn r O N h h.length x) := by apply law_precompose O phaseStepPrep storedStepCode _ _ _ _ · simp only [phaseStepPrep,params,run_both,run_compose,run_fst,run_snd,Option.bind_some,Option.map_some] rw [run_listLength] simp only [historyEncode,List.length_map] rfl · exact storedStepCode_source M₁ M₂ O hO hE₁ hE₂ r N h h.length hn x lemma phaseSampleCode_source (x : ChainIndex GS) : RealizesLaw O phaseSampleCode (fun v : PhaseSample n N => sampleEncode (observedSets n N v)) (ctx,stateEncode x.val) (DrawTree.sample (canonicalStepTree n hn r O N h h.length) (N-1) x) := by apply law_precompose O phaseSamplePrep _ _ _ _ _ · simp only [phaseSamplePrep,params,run_both,run_compose,run_fst,run_snd,run_ident,run_constant,Option.bind_some,Option.map_some] rw [run_natSub] rfl · apply law_recode O _ (mapEach snd) (fun v : PhaseSample n N => v.toList.map (fun y => (ctx,stateEncode y.val))) _ _ _ · exact law_sample O (withContext phaseStepCode) (fun y : ChainIndex GS => (ctx,stateEncode y.val)) _ (fun y => law_withContext O phaseStepCode _ ctx _ _ (phaseStepCode_source M₁ M₂ O hO hE₁ hE₂ r N L h hn y)) (N-1) x · intro v rw [run_mapEach O snd Prod.snd (fun _ => rfl)] simp only [sampleEncode,observedSets,List.map_map] rfl omit M₁ M₂ hO hE₁ hE₂ in lemma positiveTest_source : run O positiveTest ctx=some (decide (rationalHistoryPositive n N h)) := historyPositiveCode_source O h lemma phaseCode_source : RealizesLaw O phaseCode (optionEncode (fun v : PhaseSample n N => sampleEncode (observedSets n N v))) ctx (canonicalPhaseTree n hn r O N L h) := by unfold phaseCode canonicalPhaseTree apply law_choose O positiveTest _ _ _ ctx _ (decide (rationalHistoryPositive n N h)) (positiveTest_source O r N L h) by_cases hh : rationalHistoryPositive n N h · simp only [hh,decide_true,ite_true] apply law_optionBind O (retainOption startCode) (someCode phaseSampleCode) (fun x : ChainIndex GS => (ctx,stateEncode x.val)) _ ctx _ _ · exact law_retainOption O startCode _ ctx _ (startCode_source M₁ M₂ O hO hE₁ hE₂ r N L h hn) · intro x exact law_some O phaseSampleCode _ _ _ (phaseSampleCode_source M₁ M₂ O hO hE₁ hE₂ r N L h hn x) · simp only [hh,decide_false,Bool.false_eq_true,ite_false] exact law_none (a:=PhaseInput) O _ ctx lemma witnessCode_source : RealizesLaw O witnessCode (optionEncode (fun x : PlainIndex GS => stateEncode x.val.val)) ctx (canonicalWitnessTree n hn r O N L h) := by unfold witnessCode canonicalWitnessTree apply law_choose O positiveTest _ _ _ ctx _ (decide (rationalHistoryPositive n N h)) (positiveTest_source O r N L h) by_cases hh : rationalHistoryPositive n N h · simp only [hh,decide_true,ite_true] exact phaseRestartCode_source M₁ M₂ O hO hE₁ hE₂ r N L h hn · simp only [hh,decide_false,Bool.false_eq_true,ite_false] exact law_none (a:=PhaseInput) O _ ctx end open Expression namespace Expression lemma run_mapWith_source {n : ℕ} (O : IndependenceOracle n) {X : Type*} {a b c} (p : Expression (.prod a c) b) (e : X → Value a) (f : X → Value b) (ctx : Value c) (hp : ∀ x,run O p (e x,ctx)=some (f x)) (xs : List X) : run O (mapWith p) (xs.map e,ctx)=some (xs.map f) := by have hs : ∀ x (acc : List (Value b)),run O (mapStep p) (e x,(acc,ctx))=some (f x::acc,ctx) := by intro x acc simp only [mapStep,run_both,run_compose,run_fst,run_snd,Option.bind_some,Option.map_some] rw [hp] rfl have hf : ∀ (ys : List X) (acc : List (Value b)), foldValue (run O (mapStep p)) (ys.map e) (acc,ctx)=some ((ys.map f).reverse++acc,ctx) := by intro ys induction ys with | nil => intro acc; rfl | cons x ys ih => intro acc; simp [foldValue,hs,ih,List.append_assoc] simp only [mapWith,run_both,run_compose,run_fst,run_snd,run_constant,Option.bind_some,Option.map_some] change (foldValue (run O (mapStep p)) (xs.map e) ([],ctx)).bind (fun z => run O listReverse z.1)=_ rw [hf,Option.bind_some,run_listReverse] simp def ratSumCode : Expression (.list NN) NN := both ident (constant (b:=NN) (0,1)) >>> fold ratAdd def ratProductCode : Expression (.list NN) NN := both ident (constant (b:=NN) (1,1)) >>> fold ratMul lemma run_ratSumCode {n : ℕ} (O : IndependenceOracle n) (xs : List ℚ) (hx : ∀ q∈xs,0≤q) : run O ratSumCode (xs.map rationalPair)=some (rationalPair xs.sum) := by have hf : ∀ (ys : List ℚ), (∀ q∈ys,0≤q) → ∀ q,0≤q → foldValue (run O ratAdd) (ys.map rationalPair) (rationalPair q)=some (rationalPair (q+ys.sum)) := by intro ys induction ys with | nil => intro hy q hq; simp [foldValue] | cons y ys ih => intro hy q hq rw [List.map_cons,foldValue,run_ratAdd O y q (hy y (by simp)) hq,Option.bind_some] rw [ih (fun z hz => hy z (by simp [hz])) (y+q) (add_nonneg (hy y (by simp)) hq)] simp [add_left_comm,add_assoc] change foldValue (run O ratAdd) (xs.map rationalPair) (rationalPair 0)=_ simpa using hf xs hx 0 (le_refl 0) lemma run_ratProductCode {n : ℕ} (O : IndependenceOracle n) (xs : List ℚ) (hx : ∀ q∈xs,0≤q) : run O ratProductCode (xs.map rationalPair)=some (rationalPair xs.prod) := by have hf : ∀ (ys : List ℚ), (∀ q∈ys,0≤q) → ∀ q,0≤q → foldValue (run O ratMul) (ys.map rationalPair) (rationalPair q)=some (rationalPair (q*ys.prod)) := by intro ys induction ys with | nil => intro hy q hq; simp [foldValue] | cons y ys ih => intro hy q hq rw [List.map_cons,foldValue,run_ratMul O y q (hy y (by simp)) hq,Option.bind_some] rw [ih (fun z hz => hy z (by simp [hz])) (y*q) (mul_nonneg (hy y (by simp)) hq)] simp [mul_left_comm,mul_assoc] change foldValue (run O ratMul) (xs.map rationalPair) (rationalPair 1)=_ simpa using hf xs hx 1 (by norm_num) def natRatCode : Expression .nat NN := both ident (constant 1) >>> normalizeRat lemma run_natRatCode {n : ℕ} (O : IndependenceOracle n) (k : ℕ) : run O natRatCode k=some (rationalPair (k:ℚ)) := by change run O normalizeRat (k,1)=_ simpa using run_normalizeRat_pair O k 1 end Expression lemma bits_length_add_max (a b : ℕ) : (a+b).bits.length≤ max a.bits.length b.bits.length+1 := by simp only [Nat.size_eq_bits_len] apply Nat.size_le.mpr have ha := (Nat.lt_size_self a).trans_le (Nat.pow_le_pow_right (by decide : 1≤2) (Nat.le_max_left a.size b.size)) have hb := (Nat.lt_size_self b).trans_le (Nat.pow_le_pow_right (by decide : 1≤2) (Nat.le_max_right a.size b.size)) rw [pow_succ] omega def pairHeight (p : ℕ × ℕ) : ℕ := max 1 (max p.1.bits.length p.2.bits.length) lemma pairHeight_pos (p : ℕ × ℕ) : 1≤pairHeight p := Nat.le_max_left _ _ lemma pairHeight_fst (p : ℕ × ℕ) : p.1.bits.length≤pairHeight p := (Nat.le_max_left _ _).trans (Nat.le_max_right _ _) lemma pairHeight_snd (p : ℕ × ℕ) : p.2.bits.length≤pairHeight p := (Nat.le_max_right _ _).trans (Nat.le_max_right _ _) lemma width_le_pairHeight (p : ℕ × ℕ) : width (a:=NN) p≤4*pairHeight p := by obtain ⟨a,b⟩ := p have h₀ := pairHeight_pos (a,b) have h₁ := pairHeight_fst (a,b) have h₂ := pairHeight_snd (a,b) dsimp only [Prod.fst,Prod.snd] at h₁ h₂ rw [width_pair (a:=.nat) (b:=.nat),width_nat,width_nat] omega lemma pairHeight_le_width (p : ℕ × ℕ) : pairHeight p≤width (a:=NN) p := by obtain ⟨a,b⟩ := p simp only [pairHeight,width_pair (a:=.nat) (b:=.nat),width_nat] omega lemma pairHeight_normalize (a b : ℕ) : pairHeight (normalizePair a b)≤pairHeight (a,b) := by by_cases hb : b=0 · subst b simp [normalizePair,pairHeight] · rw [normalizePair,ite_eq_right hb] have h₁ := bits_length_mono (Nat.div_le_self a (Nat.gcd a b)) have h₂ := bits_length_mono (Nat.div_le_self b (Nat.gcd a b)) dsimp [pairHeight] omega lemma pairHeight_ratAdd_raw (a b c d : ℕ) : pairHeight (normalizePair (a*d+c*b) (b*d))≤pairHeight (a,b)+pairHeight (c,d)+1 := by apply (pairHeight_normalize _ _).trans have h₁ := bits_length_mul a d have h₂ := bits_length_mul c b have h₃ := bits_length_mul b d have h₄ := bits_length_add_max (a*d) (c*b) have ha := pairHeight_fst (a,b) have hb := pairHeight_snd (a,b) have hc := pairHeight_fst (c,d) have hd := pairHeight_snd (c,d) dsimp only [pairHeight] at * omega lemma pairHeight_ratMul_raw (a b c d : ℕ) : pairHeight (normalizePair (a*c) (b*d))≤pairHeight (a,b)+pairHeight (c,d) := by apply (pairHeight_normalize _ _).trans have h₁ := bits_length_mul a c have h₂ := bits_length_mul b d have ha := pairHeight_fst (a,b) have hb := pairHeight_snd (a,b) have hc := pairHeight_fst (c,d) have hd := pairHeight_snd (c,d) have hp := pairHeight_pos (a,b) dsimp only [pairHeight] at * omega lemma run_ratAdd_height {n : ℕ} (O : IndependenceOracle n) (p q y : ℕ×ℕ) (hy : run O ratAdd (p,q)=some y) : pairHeight y≤ pairHeight p+pairHeight q+1 := by obtain ⟨a,b⟩ := p obtain ⟨c,d⟩ := q rw [run_ratAdd_raw] at hy cases hy exact pairHeight_ratAdd_raw _ _ _ _ lemma run_ratMul_height {n : ℕ} (O : IndependenceOracle n) (p q y : ℕ×ℕ) (hy : run O ratMul (p,q)=some y) : pairHeight y≤ pairHeight p+pairHeight q+1 := by obtain ⟨a,b⟩ := p obtain ⟨c,d⟩ := q rw [run_ratMul_raw] at hy cases hy have hh := pairHeight_ratMul_raw a b c d omega lemma fold_pairHeight {n : ℕ} (O : IndependenceOracle n) (p : Expression (.prod NN NN) NN) (hp : ∀ x z y,run O p (x,z)=some y → pairHeight y≤pairHeight x+pairHeight z+1) (xs : List (ℕ×ℕ)) (z y : ℕ×ℕ) (hy : foldValue (run O p) xs z=some y) : pairHeight y≤pairHeight z+width (a:=.list NN) xs := by induction xs generalizing z with | nil => cases hy; simp | cons x xs ih => rw [foldValue] at hy cases he : run O p (x,z) with | none => simp [he] at hy | some w => simp only [he,Option.bind_some] at hy have hw := hp x z w he have hh := ih w hy have hx := pairHeight_le_width x rw [width_cons (a:=NN)] omega lemma controlled_pairFold (p : Expression (.prod NN NN) NN) (hp : Controlled p) (hg : ∀ {n : ℕ} (O : IndependenceOracle n) (x z y : ℕ×ℕ), run O p (x,z)=some y → pairHeight y≤pairHeight x+pairHeight z+1) : Controlled (.fold p) := by apply controlled_fold p hp (.mul (.constant 4) .input) intro n O xs z pre post he y hy have hh := fold_pairHeight O p (hg O) pre z y hy have hb := width_le_pairHeight y have hz := pairHeight_le_width z have hpre : width (a:=.list NN) pre≤width (a:=.list NN) xs := by rw [he,width_list_append]; omega simp only [SizePolynomial.eval,width_pair (a:=.list NN) (b:=NN)] omega lemma controlled_ratSum : Controlled ratSumCode := by unfold ratSumCode apply controlled_compose · control · exact controlled_pairFold ratAdd controlled_ratAdd run_ratAdd_height lemma controlled_ratProduct : Controlled ratProductCode := by unfold ratProductCode apply controlled_compose · control · exact controlled_pairFold ratMul controlled_ratMul run_ratMul_height syntax "cc" : tactic macro_rules | `(tactic| cc) => `(tactic| first | assumption | exact controlled_wordRange | exact controlled_boolNot | exact controlled_boolAnd | exact controlled_boolOr | exact controlled_natEqual | exact controlled_natEqZero | exact controlled_natSub | exact controlled_natDiv | exact controlled_natMod | exact controlled_natDivRem | exact controlled_swap | exact controlled_listLength | exact controlled_wordLength | exact controlled_fromList | exact controlled_listReverse | exact controlled_listAppend | exact controlled_productCode | exact controlled_wordGet | exact controlled_wordNot | exact controlled_wordCount | exact controlled_deficiency | exact controlled_listAll | exact controlled_splitAt | exact controlled_take | exact controlled_drop | exact controlled_headD | exact controlled_getD | exact controlled_normalizeRat | exact controlled_ratAdd | exact controlled_ratMul | exact controlled_ratDiv | exact controlled_ratLess | exact controlled_ratMinOne | exact controlled_ratSum | exact controlled_ratProduct | apply controlled_mapWith <;> cc | apply controlled_filterWith <;> cc | apply controlled_onLeft <;> cc | apply controlled_onRight <;> cc | apply controlled_letIn <;> cc | apply controlled_applyIf <;> cc | apply controlled_compose <;> cc | apply controlled_both <;> cc | apply controlled_branch <;> cc | exact controlled_atomic _ trivial) lemma controlled_boolXor : Controlled boolXor := by unfold boolXor; cc lemma controlled_singleAt : Controlled singleAt := by unfold singleAt boolXor; cc lemma controlled_fullAt : Controlled fullAt := by unfold fullAt; cc lemma controlled_emptyAt : Controlled emptyAt := by unfold emptyAt; cc lemma controlled_plainCode : Controlled plainCode := by have hs := controlled_singleAt unfold plainCode cc lemma controlled_defectAt : Controlled defectAt := by have h₁ := controlled_singleAt have h₂ := controlled_fullAt have h₃ := controlled_emptyAt unfold defectAt cc lemma controlled_defectCode : Controlled defectCode := by have hd := controlled_defectAt unfold defectCode cc lemma controlled_countWith {a b : DataType} (p : Expression (.prod a b) .bool) (hp : Controlled p) : Controlled (countWith p) := by unfold countWith; cc lemma controlled_countPlain : Controlled countPlainCode := by have hp := controlled_plainCode unfold countPlainCode apply controlled_compose · cc · apply controlled_countWith; cc lemma controlled_countDefect : Controlled countDefectCode := by have hp := controlled_defectCode unfold countDefectCode apply controlled_countWith cc lemma controlled_learningRatio : Controlled learningRatioCode := by have h₁ := controlled_countPlain have h₂ := controlled_countDefect unfold learningRatioCode cc lemma controlled_weightStep : Controlled weightStep := by have h := controlled_learningRatio unfold weightStep cc lemma polySafe_indexPairs : PolySafe indexPairs (fun S x => x≤S) := by unfold indexPairs exact polySafe_post _ _ _ (polySafe_both _ _ _ polySafe_rangeCode polySafe_rangeCode) controlled_productCode lemma controlled_wordIndexPairs : Controlled (wordLength >>> indexPairs) := by apply polySafe_controlled apply polySafe_compose _ _ _ (fun S k => k≤S) (polySafe_of_controlled _ controlled_wordLength _ .input (by intros; assumption)) polySafe_indexPairs intro n O S x hx y hy rw [run_wordLength] at hy cases hy exact hx lemma controlled_defectPairs : Controlled defectPairsCode := by have h := controlled_wordIndexPairs have hd := controlled_defectCode unfold defectPairsCode cc lemma controlled_chainCode : Controlled chainCode := by have h₁ := controlled_plainCode have h₂ := controlled_defectPairs unfold chainCode cc lemma controlled_updateAt : Controlled updateAt := by unfold updateAt; cc lemma controlled_updateWord : Controlled updateWord := by have h := controlled_updateAt unfold updateWord cc lemma controlled_splitWord : Controlled splitWord := by unfold splitWord; cc lemma controlled_exchangeWord : Controlled exchangeWord := by have h := controlled_updateWord unfold exchangeWord cc lemma controlled_exchangeSet : Controlled exchangeSetCode := by have h₁ := controlled_exchangeWord have h₂ := controlled_splitWord unfold exchangeSetCode cc lemma controlled_membersCode : Controlled membersCode := by unfold membersCode; cc lemma controlled_exchangePositions : Controlled exchangePositionsCode := by have h := controlled_membersCode unfold exchangePositionsCode cc lemma controlled_wordTake : Controlled wordTake := by unfold wordTake; cc lemma controlled_wordDrop : Controlled wordDrop := by unfold wordDrop; cc lemma controlled_clog : Controlled clogCode := by unfold clogCode; cc lemma controlled_rejectStep : Controlled rejectStep := by have h := controlled_wordTake unfold rejectStep cc lemma fold_reject_width {n : ℕ} (O : IndependenceOracle n) (xs : List Word) (v k : ℕ) (z : Bool×ℕ) (y : Value RejectState) (hy : foldValue (run O rejectStep) xs ((v,k),z)=some y) : y.1=(v,k) ∧ y.2.2.bits.length ≤ max z.2.bits.length v.bits.length := by induction xs generalizing z with | nil => cases hy; exact ⟨rfl,Nat.le_max_left _ _⟩ | cons x xs ih => rw [foldValue,run_rejectStep] at hy simp only [Option.bind_some] at hy split_ifs at hy with hh · have hi := ih _ hy refine ⟨hi.1,hi.2.trans ?_⟩ have hb := bits_length_mono hh.le dsimp only [Prod.snd] exact max_le (hb.trans (Nat.le_max_right _ _)) (Nat.le_max_right _ _) · exact ih z hy lemma controlled_rejectFold : Controlled (.fold rejectStep) := by apply controlled_fold rejectStep controlled_rejectStep (.mul (.constant 3) .input) intro n O xs z pre post he y hy obtain ⟨⟨v,k⟩,⟨b,u⟩⟩ := z change ℕ at v k u obtain ⟨⟨v',k'⟩,⟨b',u'⟩⟩ := y change ℕ at v' k' u' have hh := fold_reject_width O pre v k (b,u) ((v',k'),(b',u')) hy dsimp only [Prod.fst,Prod.snd] at hh rw [width_pair (a:=NN) (b:=Optional .nat),hh.1,width_pair (a:=.bool) (b:=.nat),width_bool,width_nat] simp only [SizePolynomial.eval,width_pair (a:=.list .word) (b:=RejectState), width_pair (a:=NN) (b:=Optional .nat),width_pair (a:=.bool) (b:=.nat), width_pair (a:=.nat) (b:=.nat),width_nat,width_bool] at * omega lemma controlled_reject : Controlled rejectCode := by have h := controlled_rejectFold unfold rejectCode cc namespace Effect lemma controlled_pure {a b : DataType} (p : Expression a b) (hp : Controlled p) : Controlled (pure p) := by unfold pure; cc lemma controlled_fail {a b : DataType} : Controlled (fail (a:=a) (b:=b)) := by unfold fail; cc lemma controlled_bind {a b c : DataType} (p : Effect a b) (q : Effect b c) (hp : Controlled p) (hq : Controlled q) : Controlled (bind p q) := by unfold bind; cc lemma controlled_keep {a b : DataType} (p : Effect a b) (hp : Controlled p) : Controlled (keep p) := by unfold keep; cc lemma controlled_letIn {a b c : DataType} (p : Effect a b) (q : Effect (.prod a b) c) (hp : Controlled p) (hq : Controlled q) : Controlled (letIn p q) := controlled_bind _ _ (controlled_keep _ hp) hq lemma controlled_draw : Controlled draw := by have h₁ := controlled_reject have h₂ := controlled_clog unfold draw cc end Effect lemma controlled_optionMap {a b : DataType} (p : Expression a b) (hp : Controlled p) : Controlled (optionMapCode p) := by unfold optionMapCode; cc lemma controlled_mapEach {a b : DataType} (p : Expression a b) (hp : Controlled p) : Controlled (mapEach p) := by unfold mapEach; cc namespace Effect lemma controlled_precompose {a b c : DataType} (p : Expression a b) (q : Effect b c) (hp : Controlled p) (hq : Controlled q) : Controlled (precompose p q) := by unfold precompose; cc lemma controlled_map {a b c : DataType} (p : Effect a b) (q : Expression b c) (hp : Controlled p) (hq : Controlled q) : Controlled (map p q) := controlled_bind p (pure q) hp (controlled_pure q hq) lemma controlled_choose {a b : DataType} (test : Expression a .bool) (p q : Effect a b) (ht : Controlled test) (hp : Controlled p) (hq : Controlled q) : Controlled (choose test p q) := by unfold choose; cc lemma controlled_withContext {a b c : DataType} (p : Effect (.prod c a) b) (hp : Controlled p) : Controlled (withContext p) := by unfold withContext apply controlled_letIn _ _ hp apply controlled_pure; cc lemma controlled_retainOption {a b : DataType} (p : Effect a (Optional b)) (hp : Controlled p) : Controlled (retainOption p) := by unfold retainOption apply controlled_letIn _ _ hp apply controlled_pure; cc syntax "ec" : tactic macro_rules | `(tactic| ec) => `(tactic| first | assumption | exact Effect.controlled_draw | apply Effect.controlled_precompose <;> ec | apply Effect.controlled_map <;> ec | apply Effect.controlled_bind <;> ec | apply Effect.controlled_letIn <;> ec | apply Effect.controlled_pure <;> cc | apply Effect.controlled_keep <;> ec | apply Effect.controlled_choose <;> ec | apply Effect.controlled_withContext <;> ec | apply Effect.controlled_retainOption <;> ec | apply controlled_optionMap <;> cc | apply controlled_mapEach <;> cc | cc) lemma controlled_bernoulli : Controlled bernoulliCode := by unfold bernoulliCode; ec lemma controlled_uniformList {a : DataType} : Controlled (uniformList (a:=a)) := by unfold uniformList; ec lemma controlled_proposal : Controlled proposal := by have h₁ := controlled_exchangePositions have h₂ := controlled_uniformList (a:=NN) unfold proposal; ec lemma controlled_someCode {a b : DataType} (p : Effect a b) (hp : Controlled p) : Controlled (someCode p) := by unfold someCode; ec lemma controlled_noneCode {a b : DataType} : Controlled (noneCode (a:=a) (b:=b)) := by unfold noneCode; ec lemma controlled_optionBind {a b c : DataType} (p : Effect a (Optional b)) (q : Effect b (Optional c)) (hp : Controlled p) (hq : Controlled q) : Controlled (optionBind p q) := by unfold optionBind; ec end Effect lemma bits_length_pow (a k : ℕ) : (a^k).bits.length≤k*a.bits.length+1 := by induction k with | zero => simp | succ k ih => rw [pow_succ] have h := bits_length_mul (a^k) a rw [Nat.add_mul,Nat.one_mul] omega lemma powStep_iterate (a k : ℕ) : ((fun z : ℕ×ℕ => (z.1,z.1*z.2))^[k]) (a,1)=(a,a^k) := by induction k with | zero => simp | succ k ih => rw [Function.iterate_succ_apply',ih,pow_succ]; simp [mul_comm] lemma controlled_powStep : Controlled powStepCode := by unfold powStepCode; control lemma polySafe_powCode : PolySafe powCode (fun S x => x.1.bits.length≤S ∧ x.2≤S) := by let g : SizePolynomial := .mul (.constant 10) (.mul (.add .input (.constant 1)) (.add .input (.constant 1))) have hg (S : ℕ) : g.eval S=10*(S+1)^2 := by simp [g,SizePolynomial.eval,pow_two] let R : ℕ → Value (.prod .nat NN) → Prop := fun S x => x.1≤S ∧ x.2.1.bits.length≤S ∧ x.2.2=1 have hi : PolySafe (iterateNat powStepCode) R := by refine polySafe_iterateNat powStepCode R (fun S z => width z≤g.eval S) (polySafe_of_controlled _ controlled_powStep _ g (by intros; assumption)) g ?_ ?_ ?_ · intro S k z hx obtain ⟨a,v⟩ := z dsimp [R] at hx rcases hx with ⟨hk,ha,rfl⟩ rw [hg,width_pair (a:=.nat) (b:=.nat),width_nat,width_nat] have h1 : (1:ℕ).bits.length=1 := rfl rw [h1] calc _ ≤ S+(2*S+1+1) := Nat.add_le_add hk (Nat.add_le_add_right (Nat.add_le_add_right (Nat.mul_le_mul_left 2 ha) 1) 1) _ ≤ _ := by nlinarith · intro n O S k z hx j hj y hy obtain ⟨a,v⟩ := z dsimp [R] at hx rcases hx with ⟨hk,ha,rfl⟩ rw [iterateM_total (run O powStepCode) (fun z : ℕ×ℕ => (z.1,z.1*z.2)) (fun _ => rfl),powStep_iterate] at hy cases hy rw [width_pair (a:=.nat) (b:=.nat),width_nat,width_nat,hg] have hh := bits_length_pow a j have hm : j*a.bits.length≤S*S := Nat.mul_le_mul (hj.trans hk) ha have hb := hh.trans (Nat.add_le_add_right hm 1) calc _ ≤ 2*S+1+(S*S+1) := Nat.add_le_add (Nat.add_le_add_right (Nat.mul_le_mul_left 2 ha) 1) hb _ ≤ _ := by nlinarith · intro n O S k z hx j hj y hy obtain ⟨a,v⟩ := z dsimp [R] at hx rcases hx with ⟨hk,ha,rfl⟩ rw [iterateM_total (run O powStepCode) (fun z : ℕ×ℕ => (z.1,z.1*z.2)) (fun _ => rfl),powStep_iterate] at hy cases hy rw [width_pair (a:=.nat) (b:=.nat),width_nat,width_nat,hg] have hh := bits_length_pow a j have hm : j*a.bits.length≤S*S := Nat.mul_le_mul (hj.le.trans hk) ha have hb := hh.trans (Nat.add_le_add_right hm 1) calc _ ≤ 2*S+1+(S*S+1) := Nat.add_le_add (Nat.add_le_add_right (Nat.mul_le_mul_left 2 ha) 1) hb _ ≤ _ := by nlinarith unfold powCode apply polySafe_compose _ _ _ R (polySafe_of_controlled _ (by control) _ (.add (.mul (.constant 3) .input) (.constant 1)) (by intro S x hx obtain ⟨a,k⟩ := x dsimp only [Prod.fst,Prod.snd] at hx rw [width_pair (a:=.nat) (b:=.nat),width_nat,width_nat] have hk : k.bits.length≤S := (bits_length_le_value k).trans hx.2 dsimp [SizePolynomial.eval] omega)) (polySafe_post _ _ R hi (by control)) intro n O S x hx y hy cases hy exact ⟨hx.2,hx.1,rfl⟩ lemma polySafe_ratPowCode : PolySafe ratPowCode (fun S x => width x.1≤S ∧ x.2≤S) := by have hwidth : ∀ S x,(width (a:=NN) x.1≤S ∧ x.2≤S) → width (a:=.prod NN .nat) x≤3*S+1 := by intro S x hx obtain ⟨q,k⟩ := x dsimp only [Prod.fst,Prod.snd] at hx rw [width_pair (a:=NN) (b:=.nat),width_nat] have hk : k.bits.length≤S := (bits_length_le_value k).trans hx.2 omega unfold ratPowCode apply polySafe_post _ _ _ _ controlled_normalizeRat apply polySafe_both · apply polySafe_compose _ _ _ _ (polySafe_of_controlled _ (by control) _ (.add (.mul (.constant 3) .input) (.constant 1)) hwidth) polySafe_powCode intro n O S x hx y hy cases hy refine ⟨?_,hx.2⟩ obtain ⟨⟨a,b⟩,k⟩ := x dsimp only [Prod.fst,Prod.snd] at hx ⊢ rw [width_pair (a:=.nat) (b:=.nat),width_nat,width_nat] at hx omega · apply polySafe_compose _ _ _ _ (polySafe_of_controlled _ (by control) _ (.add (.mul (.constant 3) .input) (.constant 1)) hwidth) polySafe_powCode intro n O S x hx y hy cases hy refine ⟨?_,hx.2⟩ obtain ⟨⟨a,b⟩,k⟩ := x dsimp only [Prod.fst,Prod.snd] at hx ⊢ rw [width_pair (a:=.nat) (b:=.nat),width_nat,width_nat] at hx omega lemma run_both_parts {n : ℕ} (O : IndependenceOracle n) {a b c : DataType} (p : Expression a b) (q : Expression a c) (x : Value a) (z : Value (.prod b c)) (hz : run O (both p q) x=some z) : run O p x=some z.1 ∧ run O q x=some z.2 := by rw [run_both] at hz cases hp : run O p x with | none => simp [hp] at hz | some y => simp only [hp,Option.bind_some] at hz cases hq : run O q x with | none => simp [hq] at hz | some w => simp only [hq,Option.map_some,Option.some.injEq] at hz subst z exact ⟨rfl,rfl⟩ lemma width_fst {a b : DataType} (x : Value (.prod a b)) : width x.1≤width x := by obtain ⟨p,q⟩ := x; simp only [width_pair]; omega lemma width_snd {a b : DataType} (x : Value (.prod a b)) : width x.2≤width x := by obtain ⟨p,q⟩ := x; simp only [width_pair]; omega lemma polySafe_ratPowerAfter {a : DataType} (p : Expression a (.prod NN .nat)) (R : ℕ → Value a → Prop) (hp : PolySafe p R) (g : SizePolynomial) (hg : ∀ {n : ℕ} (O : IndependenceOracle n) S x,R S x → ∀ y,run O p x=some y → y.2≤g.eval S) : PolySafe (p >>> ratPowCode) R := by obtain ⟨f,hf⟩ := hp let t : SizePolynomial := .add f g apply polySafe_compose p ratPowCode R (fun S y => width y.1≤t.eval S ∧ y.2≤t.eval S) ⟨f,hf⟩ (polySafe_reparam _ _ polySafe_ratPowCode t) intro n O S x hx y hy have hh := (width_fst y).trans (safe_output (hf O S x hx) hy) exact ⟨hh.trans (Nat.le_add_right _ _),(hg O S x hx y hy).trans (Nat.le_add_left _ _)⟩ lemma polySafe_preControlled {a b c : DataType} (p : Expression a b) (q : Expression b c) (R : ℕ → Value a → Prop) (Q : ℕ → Value b → Prop) (hp : Controlled p) (g : SizePolynomial) (hw : ∀ S x,R S x → width x≤g.eval S) (hq : PolySafe q Q) (hh : ∀ {n : ℕ} (O : IndependenceOracle n) S x,R S x → ∀ y,run O p x=some y → Q S y) : PolySafe (p >>> q) R := polySafe_compose _ _ _ _ (polySafe_of_controlled p hp R g hw) hq hh lemma bankEval_rest_suffix {A : Type*} (t : DrawTree A) (bank : Bank) : ∃ pre,bank=pre++(bankEval t bank).2 := by induction t generalizing bank with | leaf a => exact ⟨[],rfl⟩ | draw v k ih => cases bank with | nil => exact ⟨[],rfl⟩ | cons row bank => simp only [bankEval] split · exact ⟨[row],rfl⟩ · rename_i i hi obtain ⟨pre,hpre⟩ := ih ⟨i,rejectValue_lt _ _ _ hi⟩ bank exact ⟨row::pre,congrArg (List.cons row) hpre⟩ lemma bankEval_rest_width {A : Type*} (t : DrawTree A) (bank : Bank) : width (a:=BankData) (bankEval t bank).2≤width (a:=BankData) bank := by obtain ⟨pre,hpre⟩ := bankEval_rest_suffix t bank calc width (a:=BankData) (bankEval t bank).2 ≤ width (a:=BankData) (pre ++ (bankEval t bank).2) := by rw [width_list_append (a:=RandomRows)]; exact Nat.le_add_left _ _ _ = width (a:=BankData) bank := congrArg (width (a:=BankData)) hpre.symm namespace Effect lemma RealizesLaw.outputs {n : ℕ} {O : IndependenceOracle n} {A : Type*} {a b : DataType} {p : Effect a b} {e : A → Value b} {x : Value a} {t : DrawTree A} (h : RealizesLaw O p e x t) (bank : Bank) : ∃ y : Option A,∃ rest : Bank, run O p (x,bank)=some (optionalValue b (y.map e),rest) ∧ width (a:=BankData) rest≤width (a:=BankData) bank := by obtain ⟨u,hu,hp⟩ := h exact ⟨(bankEval u bank).1,(bankEval u bank).2,hp bank,bankEval_rest_width u bank⟩ end Effect lemma width_optionalValue {a : DataType} (x : Option (Value a)) (W : ℕ) (h : ∀ y,x=some y → width y≤W) : width (a:=Optional a) (optionalValue a x)≤width (zeroValue a)+W+3 := by cases x with | none => simp only [optionalValue,optionData,width_pair (a:=.bool) (b:=a),width_bool]; omega | some y => have hh := h y rfl simp only [optionalValue,optionData,width_pair (a:=.bool) (b:=a),width_bool] omega lemma width_optionEncode {A : Type*} {a : DataType} (e : A → Value a) (x : Option A) (W : ℕ) (h : ∀ y,width (e y)≤W) : width (optionEncode e x)≤width (zeroValue a)+W+3 := by apply width_optionalValue (x.map e) W intro y hy obtain ⟨z,hz,he⟩ := Option.map_eq_some_iff.mp hy subst y exact h z open Expression lemma learningRatio_height (xs : List (Word×Word)) (p r : ℕ) : pairHeight (rationalPair (learningRatio xs p r))≤width (a:=SampleData) xs+1 := by rw [learningRatio,rationalPair_div] apply (pairHeight_normalize _ _).trans have ha := bits_length_le_value (countPlainValue xs) have hb := bits_length_le_value (countDefectValue xs p r) have hc : countPlainValue xs≤xs.length := List.countP_le_length have hd : countDefectValue xs p r≤xs.length := List.countP_le_length have he := list_length_le_width (a:=StateData) xs dsimp only [pairHeight] omega lemma run_weightStep_raw {n : ℕ} (O : IndependenceOracle n) (p r a b : ℕ) (xs : List (Word×Word)) : run O weightStep (xs,((p,r),(a,b)))=some ((p,r), if p=r then (a,b) else normalizePair (a*(rationalPair (learningRatio xs p r)).1) (b*(rationalPair (learningRatio xs p r)).2)) := by simp only [weightStep,run_both,run_compose,run_fst,run_snd,Option.bind_some,run_applyIf] rw [run_natEqual] by_cases h : p=r · simp [h] · simp only [h,decide_false,Option.bind_some,Bool.false_eq_true,ite_false,Option.map_some] rw [run_learningRatio] simp only [Option.bind_some,Option.map_some] rw [run_ratMul_raw]; rfl lemma weightStep_height {n : ℕ} (O : IndependenceOracle n) (xs : Value SampleData) (z y : Value (.prod NN NN)) (hy : run O weightStep (xs,z)=some y) : y.1=z.1 ∧ pairHeight y.2≤pairHeight z.2+width xs+1 := by obtain ⟨⟨p,r⟩,⟨a,b⟩⟩ := z rw [run_weightStep_raw] at hy cases hy refine ⟨rfl,?_⟩ split_ifs with h · omega · have hh := pairHeight_ratMul_raw a b (rationalPair (learningRatio xs p r)).1 (rationalPair (learningRatio xs p r)).2 have hl := learningRatio_height xs p r simpa only [Prod.eta,Prod.snd,Nat.add_assoc] using hh.trans (Nat.add_le_add_left hl (pairHeight (a,b))) lemma fold_weight_height {n : ℕ} (O : IndependenceOracle n) (xs : Value HistoryData) (z y : Value (.prod NN NN)) (hy : foldValue (run O weightStep) xs z=some y) : y.1=z.1 ∧ pairHeight y.2≤pairHeight z.2+width xs := by induction xs generalizing z with | nil => cases hy; exact ⟨rfl,by simp⟩ | cons x xs ih => rw [foldValue] at hy cases he : run O weightStep (x,z) with | none => simp [he] at hy | some w => simp only [he,Option.bind_some] at hy have h₁ := weightStep_height O x z w he have h₂ := ih w hy refine ⟨h₂.1.trans h₁.1,?_⟩ rw [width_cons (a:=SampleData)] omega lemma controlled_weightFold : Controlled (.fold weightStep) := by apply controlled_fold weightStep controlled_weightStep (.mul (.constant 6) .input) intro n O xs z pre post he y hy have hh := fold_weight_height O pre z y hy have hp : width (a:=HistoryData) pre≤width (a:=HistoryData) xs := by rw [he,width_list_append]; omega have hw := width_le_pairHeight y.2 have hz := pairHeight_le_width z.2 rw [width_pair (a:=NN) (b:=NN),hh.1] simp only [SizePolynomial.eval,width_pair (a:=HistoryData) (b:=.prod NN NN),width_pair (a:=NN) (b:=NN)] omega lemma controlled_historyWeight : Controlled historyWeightCode := by have h := controlled_weightFold unfold historyWeightCode cc lemma controlled_multiplier : Controlled multiplierCode := by have h₁ := controlled_historyWeight have h₂ := controlled_defectPairs have h₃ := controlled_plainCode unfold multiplierCode cc open Expression lemma controlled_rho : Controlled rhoCode := by unfold rhoCode; cc lemma run_deficiency_le {n : ℕ} (O : IndependenceOracle n) (r : ℕ) (x y : Word) (z : ℕ) (hz : run O deficiencyCode (r,(x,y))=some z) : z≤x.length+r := by simp only [deficiencyCode,run_compose,run_both,run_fst,run_snd,Option.bind_some,Option.map_some] at hz rw [run_wordLength,run_wordCount,run_wordNot] at hz simp only [run,Option.bind_some,Option.map_some] at hz split_ifs at hz <;> simp_all only [Option.bind_none,Option.map_none,Option.bind_some,Option.map_some] <;> try contradiction rw [run_natSub] at hz cases hz exact Nat.sub_le _ _ def weightSmall (S : ℕ) (x : Value WeightInput) : Prop := width x≤S ∧ x.1.1.1≤S ∧ x.1.1.2≤S lemma polySafe_anneal : PolySafe annealCode weightSmall := by have hrho := controlled_rho have hi : PolySafe (both (snd >>> fst >>> wordLength >>> rhoCode) (fst >>> fst >>> snd) >>> ratPowCode) weightSmall := by apply polySafe_ratPowerAfter _ _ (polySafe_of_controlled _ (by cc) _ .input (by intro S x hx; exact hx.1)) .input intro n O S x hx y hy have hh := (run_both_parts O _ _ x y hy).2 change some x.1.1.2=some y.2 at hh exact (Option.some.inj hh) ▸ hx.2.2 unfold annealCode apply polySafe_ratPowerAfter _ _ (polySafe_both _ _ _ hi (polySafe_of_controlled _ (by cc) _ .input (by intro S x hx; exact hx.1))) (.mul (.constant 2) .input) intro n O S x hx y hy have hh := (run_both_parts O _ _ x y hy).2 change run O deficiencyCode (x.1.1.1,x.2)=some y.2 at hh have hb := run_deficiency_le O x.1.1.1 x.2.1 x.2.2 y.2 hh have hw : x.2.1.length≤S := (width_fst (a:=.word) (b:=.word) x.2).trans ((width_snd x).trans hx.1) dsimp only [SizePolynomial.eval] exact hb.trans ((Nat.add_le_add hw hx.2.1).trans_eq (by omega)) lemma polySafe_weight : PolySafe weightCode weightSmall := by have hm := controlled_multiplier unfold weightCode exact polySafe_post _ _ _ (polySafe_both _ _ _ (polySafe_of_controlled _ (by cc) _ .input (by intro S x hx; exact hx.1)) polySafe_anneal) controlled_ratMul abbrev OraclePredicate (a : DataType) := (n : ℕ) → IndependenceOracle n → ℕ → Value a → Prop def OracleSafe {a b : DataType} (p : Expression a b) (R : OraclePredicate a) : Prop := ∃ f : SizePolynomial,∀ {n : ℕ} (O : IndependenceOracle n) S x,R n O S x → Safe O (f.eval S) p x lemma oracleSafe_lift {a b : DataType} (p : Expression a b) (R : ℕ → Value a → Prop) (h : PolySafe p R) : OracleSafe p (fun _ _ => R) := h lemma oracleSafe_controlled {a b : DataType} (p : Expression a b) (hp : Controlled p) (R : OraclePredicate a) (g : SizePolynomial) (hg : ∀ n O S x,R n O S x → width x≤g.eval S) : OracleSafe p R := by obtain ⟨f,hf⟩ := hp refine ⟨f.subst g,fun O S x hx => ?_⟩ apply safe_mono p x (hf O x) rw [SizePolynomial.eval_subst] exact f.monotone (hg _ O S x hx) lemma oracleSafe_mono {a b : DataType} (p : Expression a b) {R Q : OraclePredicate a} (hp : OracleSafe p Q) (h : ∀ n O S x,R n O S x → Q n O S x) : OracleSafe p R := by obtain ⟨f,hf⟩ := hp exact ⟨f,fun O S x hx => hf O S x (h _ O S x hx)⟩ lemma oracleSafe_reparam {a b : DataType} (p : Expression a b) (R : OraclePredicate a) (hp : OracleSafe p R) (g : SizePolynomial) : OracleSafe p (fun n O S x => R n O (g.eval S) x) := by obtain ⟨f,hf⟩ := hp exact ⟨f.subst g,fun O S x hx => by rw [SizePolynomial.eval_subst]; exact hf O _ x hx⟩ lemma oracleSafe_compose {a b c : DataType} (p : Expression a b) (q : Expression b c) (R : OraclePredicate a) (Q : OraclePredicate b) (hp : OracleSafe p R) (hq : OracleSafe q Q) (h : ∀ n O S x,R n O S x → ∀ y,run O p x=some y → Q n O S y) : OracleSafe (p >>> q) R := by obtain ⟨f,hf⟩ := hp obtain ⟨g,hg⟩ := hq refine ⟨.add f g,fun O S x hx => ?_⟩ apply safe_compose O p q x · exact safe_mono p x (hf O S x hx) (Nat.le_add_right _ _) · intro y hy exact safe_mono q y (hg O S y (h _ O S x hx y hy)) (Nat.le_add_left _ _) lemma oracleSafe_both {a b c : DataType} (p : Expression a b) (q : Expression a c) (R : OraclePredicate a) (hp : OracleSafe p R) (hq : OracleSafe q R) : OracleSafe (both p q) R := by obtain ⟨f,hf⟩ := hp obtain ⟨g,hg⟩ := hq refine ⟨.add (.mul (.constant 3) (.add f g)) (.constant 1),fun O S x hx => ?_⟩ apply safe_both O p q x · exact safe_mono p x (hf O S x hx) (Nat.le_add_right _ _) · exact safe_mono q x (hg O S x hx) (Nat.le_add_left _ _) lemma oracleSafe_post {a b c : DataType} (p : Expression a b) (q : Expression b c) (R : OraclePredicate a) (hp : OracleSafe p R) (hq : Controlled q) : OracleSafe (p >>> q) R := by obtain ⟨f,hf⟩ := hp apply oracleSafe_compose p q R (fun _ _ S y => width y≤f.eval S) ⟨f,hf⟩ (oracleSafe_controlled q hq _ f (by intros; assumption)) intro n O S x hx y hy exact safe_output (hf O S x hx) hy lemma oracleSafe_pull {a b c : DataType} (p : Expression a b) (q : Expression b c) (R : OraclePredicate a) (Q : OraclePredicate b) (hp : Controlled p) (g : SizePolynomial) (hw : ∀ n O S x,R n O S x → width x≤g.eval S) (hq : OracleSafe q Q) (hh : ∀ n O S x,R n O S x → ∀ y,run O p x=some y → Q n O S y) : OracleSafe (p >>> q) R := oracleSafe_compose p q R Q (oracleSafe_controlled p hp R g hw) hq hh lemma oracleSafe_input_bound {a b : DataType} (p : Expression a b) (R : OraclePredicate a) (hp : OracleSafe p R) : ∃ f : SizePolynomial,∀ n O S x,R n O S x → width x≤f.eval S := by obtain ⟨f,hf⟩ := hp exact ⟨f,fun _ O S x hx => safe_input (hf O S x hx)⟩ lemma oracleSafe_applyIf {a b : DataType} (t : Expression a .bool) (p q : Expression a b) (R : OraclePredicate a) (ht : OracleSafe t R) (hp : OracleSafe p (fun n O S x => R n O S x ∧ run O t x=some false)) (hq : OracleSafe q (fun n O S x => R n O S x ∧ run O t x=some true)) : OracleSafe (applyIf t p q) R := by have hid : OracleSafe (ident (a:=a)) R := by obtain ⟨f,hf⟩ := oracleSafe_input_bound t R ht exact oracleSafe_controlled _ (by cc) R f hf have hboth := oracleSafe_both t ident R ht hid obtain ⟨f,hf⟩ := hboth obtain ⟨g,hg⟩ := hp obtain ⟨k,hk⟩ := hq unfold applyIf apply oracleSafe_compose (both t ident) (branch p q) R (fun n O S z => width z≤f.eval S ∧ R n O S z.2 ∧ run O t z.2=some z.1) ⟨f,hf⟩ · refine ⟨.add f (.add g k),fun O S z hz => ?_⟩ obtain ⟨v,x⟩ := z refine ⟨hz.1.trans (Nat.le_add_right _ _),?_,?_⟩ · intro y hy cases v · exact (safe_output (hg O S x ⟨hz.2.1,hz.2.2⟩) hy).trans (by dsimp [SizePolynomial.eval]; omega) · exact (safe_output (hk O S x ⟨hz.2.1,hz.2.2⟩) hy).trans (by dsimp [SizePolynomial.eval]; omega) · cases v · exact safe_mono p x (hg O S x ⟨hz.2.1,hz.2.2⟩) (by dsimp [SizePolynomial.eval]; omega) · exact safe_mono q x (hk O S x ⟨hz.2.1,hz.2.2⟩) (by dsimp [SizePolynomial.eval]; omega) · intro n O S x hx z hz have hh := run_both_parts O t ident x z hz have he : x=z.2 := Option.some.inj hh.2 exact ⟨safe_output (hf O S x hx) hz,he ▸ hx,he ▸ hh.1⟩ lemma oracleSafe_fold {a b : DataType} (p : Expression (.prod a b) b) (R : OraclePredicate (.prod (.list a) b)) (Q : OraclePredicate (.prod a b)) (hp : OracleSafe p Q) (g : SizePolynomial) (hinput : ∀ {n : ℕ} (O : IndependenceOracle n) S x,R n O S x → width x≤g.eval S) (hacc : ∀ {n : ℕ} (O : IndependenceOracle n) S xs z,R n O S (xs,z) → ∀ pre post,xs=pre++post → ∀ y,foldValue (run O p) pre z=some y → width y≤g.eval S) (hstep : ∀ {n : ℕ} (O : IndependenceOracle n) S xs z,R n O S (xs,z) → ∀ pre x post,xs=pre++x::post → ∀ y,foldValue (run O p) pre z=some y → Q n O S (x,y)) : OracleSafe (.fold p) R := by obtain ⟨f,hf⟩ := hp refine ⟨.add f g,fun O S x hx => ?_⟩ obtain ⟨xs,z⟩ := x refine ⟨(hinput O S (xs,z) hx).trans (Nat.le_add_left _ _),?_,?_⟩ · intro y hy exact (hacc O S xs z hx xs [] (by simp) y hy).trans (Nat.le_add_left _ _) · apply foldSafe_prefix intro pre x post he y hy exact safe_mono p (x,y) (hf O S (x,y) (hstep O S xs z hx pre x post he y hy)) (Nat.le_add_right _ _) lemma oracleSafe_iterateNat {a : DataType} (p : Expression a a) (R : OraclePredicate (.prod .nat a)) (Q : OraclePredicate a) (hp : OracleSafe p Q) (g : SizePolynomial) (hinput : ∀ {n : ℕ} (O : IndependenceOracle n) S k z,R n O S (k,z) → k+width (a:=a) z≤g.eval S) (hacc : ∀ {n : ℕ} (O : IndependenceOracle n) S k z,R n O S (k,z) → ∀ j,j≤k → ∀ y,iterateM (run O p) j z=some y → width (a:=a) y≤g.eval S) (hbody : ∀ {n : ℕ} (O : IndependenceOracle n) S k z,R n O S (k,z) → ∀ j,j k≤g.eval S) (oracleSafe_controlled Expression.fst (by control) R T (fun n O => hnatwidth O)) (oracleSafe_reparam unary (fun _ _ S k => k≤S) (oracleSafe_lift _ _ polySafe_unary) g) intro n O S x hx y hy obtain ⟨k,z⟩ := x simp only [run_fst, Option.some.injEq] at hy subst y have hh : k+width (a:=a) z≤g.eval S := hinput O S k z hx exact (Nat.le_add_right k (width (a:=a) z)).trans hh · exact oracleSafe_controlled Expression.snd (by control) R T (fun n O => hnatwidth O) let Rw : OraclePredicate (.prod .word a) := fun n O S x => R n O S (x.1.length,x.2) let Rl : OraclePredicate (.prod (.list .bool) a) := fun n O S x => R n O S (x.1.length,x.2) have hw : ∀ {n : ℕ} (O : IndependenceOracle n) S x,Rw n O S x → width x≤T.eval S := by intro n O S x hx obtain ⟨w,z⟩ := x have hh : w.length+width (a:=a) z≤g.eval S := hinput O S w.length z hx rw [width_pair (a:=.word) (b:=a),width_word] dsimp [T,SizePolynomial.eval] omega have hfold : OracleSafe (.fold (snd >>> p)) Rl := by refine oracleSafe_fold (Expression.snd (a:=.bool) >>> p) Rl (fun n O S x => width x≤T.eval S ∧ Q n O S x.2) ?_ T ?_ ?_ ?_ · apply oracleSafe_compose _ _ _ Q (oracleSafe_controlled Expression.snd (by control) _ T (by intro n O S x hx; exact hx.1)) hp intro n O S x hx y hy cases hy exact hx.2 · intro n O S x hx obtain ⟨xs,z⟩ := x have hh : xs.length+width (a:=a) z≤g.eval S := hinput O S xs.length z hx rw [width_pair (a:=.list .bool) (b:=a),width_list_bool] dsimp [T,SizePolynomial.eval] omega · intro n O S xs z hx pre post he y hy rw [foldValue_iterateM] at hy have hj : pre.length≤xs.length := by rw [he,List.length_append]; omega have hh := hacc O S xs.length z hx pre.length hj y hy dsimp [T,SizePolynomial.eval] omega · intro n O S xs z hx pre b post he y hy rw [foldValue_iterateM] at hy have hj : pre.length hw O)) hfold intro n O S x hx y hy cases hy exact hx · intro n O S x hx y hy obtain ⟨k,z⟩ := x obtain ⟨w,hw,hk⟩ := run_unary O k simp only [onLeft,run_both,run_compose,run_fst,run_snd,Option.bind_some,hw,Option.map_some] at hy cases hy change R n O S (w.length,z) rwa [hk] namespace Effect def bankScope {a : DataType} (R : OraclePredicate a) : OraclePredicate (.prod a BankData) := fun n O S x => R n O S x.1 ∧ width (a:=BankData) x.2≤S lemma scope_width {a b : DataType} (p : Expression a b) (R : OraclePredicate a) (hp : OracleSafe p R) : ∃ f : SizePolynomial,∀ n O S x,bankScope R n O S x → width x≤f.eval S := by obtain ⟨f,hf⟩ := oracleSafe_input_bound p R hp refine ⟨.add (.mul (.constant 2) f) (.add .input (.constant 1)),?_⟩ intro n O S x hx have hh := hf n O S x.1 hx.1 have hb : width (a:=BankData) x.2≤S := hx.2 rw [width_pair (a:=a) (b:=BankData)] dsimp only [SizePolynomial.eval] omega lemma safe_scope_fst {a b : DataType} (p : Expression a b) (R : OraclePredicate a) (hp : OracleSafe p R) : OracleSafe (fst (b:=BankData) >>> p) (bankScope R) := by obtain ⟨f,hf⟩ := scope_width p R hp apply oracleSafe_pull _ _ _ R (by cc) f hf hp intro n O S x hx y hy cases hy exact hx.1 lemma safe_scope_controlled {a b c : DataType} (p : Expression a b) (q : Expression (.prod a BankData) c) (R : OraclePredicate a) (hp : OracleSafe p R) (hq : Controlled q) : OracleSafe q (bankScope R) := by obtain ⟨f,hf⟩ := scope_width p R hp exact oracleSafe_controlled q hq _ f hf lemma oracleSafe_pure {a b : DataType} (p : Expression a b) (R : OraclePredicate a) (hp : OracleSafe p R) : OracleSafe (pure p) (bankScope R) := by unfold pure apply oracleSafe_both · apply oracleSafe_both · exact safe_scope_controlled p _ R hp (by cc) · exact safe_scope_fst p R hp · exact safe_scope_controlled p _ R hp (by cc) lemma oracleSafe_precompose {a b c : DataType} (p : Expression a b) (q : Effect b c) (R : OraclePredicate a) (Q : OraclePredicate b) (hp : OracleSafe p R) (hq : OracleSafe q (bankScope Q)) (h : ∀ n O S x,R n O S x → ∀ y,run O p x=some y → Q n O S y) : OracleSafe (precompose p q) (bankScope R) := by unfold precompose onLeft apply oracleSafe_compose _ _ _ (bankScope Q) (oracleSafe_both _ _ _ (safe_scope_fst p R hp) (safe_scope_controlled p _ R hp (by cc))) hq intro n O S x hx y hy have hh := run_both_parts O (fst >>> p) snd x y hy have hp' : run O p x.1=some y.1 := hh.1 have hb : x.2=y.2 := Option.some.inj hh.2 exact ⟨h n O S x.1 hx.1 y.1 hp',hb ▸ hx.2⟩ lemma oracleSafe_keep {a b : DataType} (p : Effect a b) (R : OraclePredicate (.prod a BankData)) (hp : OracleSafe p R) : OracleSafe (keep p) R := by obtain ⟨f,hf⟩ := oracleSafe_input_bound p R hp unfold keep Expression.letIn apply oracleSafe_post · exact oracleSafe_both _ _ _ (oracleSafe_controlled _ (by cc) R f hf) hp · cc lemma oracleSafe_bind {a b c : DataType} (p : Effect a b) (q : Effect b c) (R : OraclePredicate a) (Q : OraclePredicate b) (hp : OracleSafe p (bankScope R)) (hq : OracleSafe q (bankScope Q)) (h : ∀ n O S x bank,R n O S x → width (a:=BankData) bank≤S → ∀ y rest, run O p (x,bank)=some ((true,y),rest) → Q n O S y ∧ width (a:=BankData) rest≤S) : OracleSafe (bind p q) (bankScope R) := by obtain ⟨f,hf⟩ := hp let T : OraclePredicate (.prod (Optional b) BankData) := fun n O S z => ∃ x bank,bankScope R n O S (x,bank) ∧ run O p (x,bank)=some z have hw : ∀ n O S z,T n O S z → width z≤f.eval S := by intro n O S z hz obtain ⟨x,bank,hx,he⟩ := hz exact safe_output (hf O S (x,bank) hx) he unfold bind apply oracleSafe_compose p _ (bankScope R) T ⟨f,hf⟩ · apply oracleSafe_applyIf _ _ _ T · exact oracleSafe_controlled _ (by cc) T f hw · exact oracleSafe_controlled _ (by cc) _ f (by intro n O S z hz; exact hw n O S z hz.1) · apply oracleSafe_pull _ q _ (bankScope Q) (by cc) f (by intro n O S z hz; exact hw n O S z hz.1) hq intro n O S z hz y hy obtain ⟨⟨flag,v⟩,rest⟩ := z have hv : flag=true := Option.some.inj hz.2 subst flag have hy' : (v,rest)=y := Option.some.inj hy subst y obtain ⟨x,bank,hx,he⟩ := hz.1 exact h n O S x bank hx.1 hx.2 v rest he · intro n O S x hx z hz exact ⟨x.1,x.2,hx,hz⟩ lemma RealizesLaw.output_some {n : ℕ} {O : IndependenceOracle n} {A : Type*} {a b : DataType} {p : Effect a b} {e : A → Value b} {x : Value a} {t : DrawTree A} (h : RealizesLaw O p e x t) (bank : Bank) (y : Value b) (rest : Bank) (hy : run O p (x,bank)=some ((true,y),rest)) : ∃ v,y=e v ∧ width (a:=BankData) rest≤width (a:=BankData) bank := by obtain ⟨v,r,he,hw⟩ := h.outputs bank rw [hy] at he have he' := Option.some.inj he cases v with | none => cases (congrArg (fun z => z.1.1) he') | some v => have hry : rest=r := congrArg Prod.snd he' have hyy : y=e v := congrArg (fun z => z.1.2) he' exact ⟨v,hyy,hry ▸ hw⟩ end Effect end MachineCode namespace DrawTree lemma All.mono {A : Type*} {t : DrawTree A} {P Q : A → Prop} (h : All P t) (hq : ∀ x,P x → Q x) : All Q t := by induction t with | leaf x => exact hq x h | draw v k ih => exact fun i => ih i (h i) lemma all_bind_of_all {A B : Type*} (t : DrawTree A) (f : A → DrawTree B) (P : A → Prop) (Q : B → Prop) (ht : All P t) (hf : ∀ x,P x → All Q (f x)) : All Q (t.bind f) := by induction t with | leaf x => exact hf x ht | draw v k ih => exact fun i => ih i (ht i) lemma all_map_of_all {A B : Type*} (t : DrawTree A) (f : A → B) (P : A → Prop) (Q : B → Prop) (ht : All P t) (hf : ∀ x,P x → Q (f x)) : All Q (t.map f) := all_bind_of_all t _ P Q ht hf end DrawTree namespace MachineCode lemma bankEval_all {A : Type*} (t : DrawTree A) (P : A → Prop) (ht : DrawTree.All P t) (bank : Bank) (x : A) (hx : (bankEval t bank).1=some x) : P x := by induction t generalizing bank with | leaf a => have he : a=x := Option.some.inj hx exact he ▸ ht | draw v k ih => cases bank with | nil => cases hx | cons row bank => simp only [bankEval] at hx split at hx · cases hx · exact ih _ (ht _) bank hx open Expression namespace Effect lemma RealizesLaw.outputs_all {n : ℕ} {O : IndependenceOracle n} {A : Type*} {a b : DataType} {p : Effect a b} {e : A → Value b} {x : Value a} {t : DrawTree A} (h : RealizesLaw O p e x t) (P : A → Prop) (ht : DrawTree.All P t) (bank : Bank) : ∃ y : Option A,∃ rest : Bank, run O p (x,bank)=some (optionalValue b (y.map e),rest) ∧ width (a:=BankData) rest≤width (a:=BankData) bank ∧ ∀ v,y=some v → P v := by obtain ⟨u,hu,hp⟩ := h refine ⟨(bankEval u bank).1,(bankEval u bank).2,hp bank,bankEval_rest_width u bank,?_⟩ intro v hv exact bankEval_all u P (hu.all P ht) bank v hv lemma RealizesLaw.output_some_all {n : ℕ} {O : IndependenceOracle n} {A : Type*} {a b : DataType} {p : Effect a b} {e : A → Value b} {x : Value a} {t : DrawTree A} (h : RealizesLaw O p e x t) (P : A → Prop) (ht : DrawTree.All P t) (bank : Bank) (y : Value b) (rest : Bank) (hy : run O p (x,bank)=some ((true,y),rest)) : ∃ v,y=e v ∧ P v ∧ width (a:=BankData) rest≤width (a:=BankData) bank := by obtain ⟨v,r,he,hw,hv⟩ := h.outputs_all P ht bank rw [hy] at he have hh := Option.some.inj he cases v with | none => cases (congrArg (fun z => z.1.1) hh) | some v => have hry : rest=r := congrArg Prod.snd hh have hyy : y=e v := congrArg (fun z => z.1.2) hh exact ⟨v,hyy,hv v rfl,hry ▸ hw⟩ lemma RealizesLaw.run_bound {n : ℕ} {O : IndependenceOracle n} {A : Type*} {a b : DataType} {p : Effect a b} {e : A → Value b} {x : Value a} {t : DrawTree A} (h : RealizesLaw O p e x t) (W : ℕ) (R : Value b → Prop) (ht : DrawTree.All (fun v => width (e v)≤W ∧ R (e v)) t) (bank : Bank) (y : Value (.prod (Optional b) BankData)) (hy : run O p (x,bank)=some y) : width y≤2*(width (zeroValue b)+W+3)+1+width (a:=BankData) bank ∧ (y.1.1=true → R y.1.2) := by obtain ⟨v,rest,he,hrest,hv⟩ := h.outputs_all _ ht bank have he' : y=(optionalValue b (v.map e),rest) := Option.some.inj (hy.symm.trans he) subst y constructor · have hw : width (optionalValue b (v.map e))≤width (zeroValue b)+W+3 := by apply width_optionalValue intro z hz obtain ⟨u,hu,hz⟩ := Option.map_eq_some_iff.mp hz subst z exact (hv u hu).1 rw [width_pair (a:=Optional b) (b:=BankData)] omega · cases v with | none => intro h; cases h | some z => intro _; exact (hv z rfl).2 lemma RealizesLaw.rest_width {n : ℕ} {O : IndependenceOracle n} {A : Type*} {a b : DataType} {p : Effect a b} {e : A → Value b} {x : Value a} {t : DrawTree A} (h : RealizesLaw O p e x t) (bank : Bank) (y : Value (.prod (Optional b) BankData)) (hy : run O p (x,bank)=some y) : width (a:=BankData) y.2≤width (a:=BankData) bank := by obtain ⟨v,rest,he,hrest⟩ := h.outputs bank have he' : y=(optionalValue b (v.map e),rest) := Option.some.inj (hy.symm.trans he) exact he' ▸ hrest def BankMonotone {a b : DataType} (p : Effect a b) : Prop := ∀ {n : ℕ} (O : IndependenceOracle n) (x : Value a) (bank : Bank) z, run O p (x,bank)=some z → width (a:=BankData) z.2≤width (a:=BankData) bank lemma bank_pure {a b : DataType} (p : Expression a b) : BankMonotone (pure p) := by intro n O x bank z hz have hh := (run_both_parts (a:=.prod a BankData) (b:=Optional b) (c:=BankData) O (both (constant (b:=.bool) true) (fst >>> p)) snd (x,bank) z hz).2 have he : bank=z.2 := Option.some.inj hh exact he ▸ le_rfl lemma bank_fail {a b : DataType} : BankMonotone (fail (a:=a) (b:=b)) := by intro n O x bank z hz cases hz exact le_rfl lemma bank_bind {a b c : DataType} (p : Effect a b) (q : Effect b c) (hp : BankMonotone p) (hq : BankMonotone q) : BankMonotone (bind p q) := by intro n O x bank z hz rw [bind,run_compose] at hz cases he : run O p (x,bank) with | none => simp [he] at hz | some y => simp only [he,Option.bind_some] at hz obtain ⟨⟨v,y⟩,rest⟩ := y have hb := hp O x bank ((v,y),rest) he cases v · cases hz; exact hb · exact (hq O y rest z hz).trans hb lemma run_keep_value {n : ℕ} (O : IndependenceOracle n) {a b : DataType} (p : Effect a b) (x : Value a) (bank : Bank) (v : Value (.prod (Optional b) BankData)) (hp : run O p (x,bank)=some v) : run O (keep p) (x,bank)=some ((if v.1.1 then optionalValue (.prod a b) (some (x,v.1.2)) else optionalValue (.prod a b) none),v.2) := by rw [keep,run_letIn,hp] obtain ⟨⟨flag,y⟩,rest⟩ := v cases flag <;> rfl lemma run_keep_some {n : ℕ} (O : IndependenceOracle n) {a b : DataType} (p : Effect a b) (x : Value a) (bank : Bank) (x' : Value a) (y : Value b) (rest : Bank) (h : run O (keep p) (x,bank)=some ((true,(x',y)),rest)) : x'=x ∧ run O p (x,bank)=some ((true,y),rest) := by cases he : run O p (x,bank) with | none => simp only [keep,run_letIn,he,Option.bind_none] at h; contradiction | some v => rw [run_keep_value O p x bank v he] at h obtain ⟨⟨flag,y'⟩,r⟩ := v cases flag · cases h · cases h exact ⟨rfl,rfl⟩ lemma bank_keep {a b : DataType} (p : Effect a b) (hp : BankMonotone p) : BankMonotone (keep p) := by intro n O x bank z hz cases he : run O p (x,bank) with | none => simp only [keep,run_letIn,he,Option.bind_none] at hz; contradiction | some v => rw [run_keep_value O p x bank v he] at hz cases hz exact hp O x bank v he lemma bank_letIn {a b c : DataType} (p : Effect a b) (q : Effect (.prod a b) c) (hp : BankMonotone p) (hq : BankMonotone q) : BankMonotone (letIn p q) := bank_bind _ _ (bank_keep p hp) hq lemma bank_precompose {a b c : DataType} (p : Expression a b) (q : Effect b c) (hq : BankMonotone q) : BankMonotone (precompose p q) := by intro n O x bank z hz cases he : run O p x with | none => simp only [precompose,onLeft,run_compose,run_both,run_fst,run_snd,Option.bind_some,he,Option.bind_none] at hz; contradiction | some y => rw [run_precompose O p q x y bank he] at hz exact hq O y bank z hz lemma bank_map {a b c : DataType} (p : Effect a b) (q : Expression b c) (hp : BankMonotone p) : BankMonotone (map p q) := bank_bind _ _ hp (bank_pure q) lemma bank_choose {a b : DataType} (t : Expression a .bool) (p q : Effect a b) (hp : BankMonotone p) (hq : BankMonotone q) : BankMonotone (choose t p q) := by intro n O x bank z hz cases he : run O t x with | none => simp only [choose,run_applyIf,run_compose,run_fst,Option.bind_some,he,Option.bind_none] at hz; contradiction | some flag => rw [run_choose O t p q x bank flag he] at hz cases flag · exact hp O x bank z hz · exact hq O x bank z hz lemma bank_draw : BankMonotone draw := by intro n O v bank z hz rw [run_draw] at hz cases hz exact width_drop (a:=RandomRows) bank 1 end Effect open Expression abbrev Attribute (a : DataType) := ℕ → Value a → Prop def Attribute.Mono {a : DataType} (R : Attribute a) : Prop := ∀ S T,S≤T → ∀ x,R S x → R T x def AttrSafe {a b : DataType} (p : Expression a b) (R : Attribute a) : Prop := PolySafe p (fun S x => width x≤S ∧ R S x) lemma attrSafe_controlled {a b : DataType} (p : Expression a b) (hp : Controlled p) (R : Attribute a) : AttrSafe p R := polySafe_of_controlled p hp _ .input (by intro S x hx; exact hx.1) lemma attrSafe_mono {a b : DataType} (p : Expression a b) {R Q : Attribute a} (hp : AttrSafe p Q) (h : ∀ S x,R S x → Q S x) : AttrSafe p R := polySafe_mono p hp (by intro S x hx; exact ⟨hx.1,h S x hx.2⟩) lemma attrSafe_compose {a b c : DataType} (p : Expression a b) (q : Expression b c) (R : Attribute a) (Q : Attribute b) (hp : AttrSafe p R) (hq : AttrSafe q Q) (hm : Q.Mono) (h : ∀ {n : ℕ} (O : IndependenceOracle n) S x,R S x → ∀ y,run O p x=some y → Q S y) : AttrSafe (p >>> q) R := by obtain ⟨f,hf⟩ := hp let g : SizePolynomial := .add f .input apply polySafe_compose p q _ (fun S y => width y≤g.eval S ∧ Q (g.eval S) y) ⟨f,hf⟩ (polySafe_reparam q _ hq g) intro n O S x hx y hy exact ⟨(safe_output (hf O S x hx) hy).trans (Nat.le_add_right _ _), hm S _ (Nat.le_add_left _ _) y (h O S x hx.2 y hy)⟩ lemma attrSafe_both {a b c : DataType} (p : Expression a b) (q : Expression a c) (R : Attribute a) (hp : AttrSafe p R) (hq : AttrSafe q R) : AttrSafe (both p q) R := polySafe_both p q _ hp hq lemma attrSafe_post {a b c : DataType} (p : Expression a b) (q : Expression b c) (R : Attribute a) (hp : AttrSafe p R) (hq : Controlled q) : AttrSafe (p >>> q) R := polySafe_post p q _ hp hq lemma attrSafe_pull {a b c : DataType} (p : Expression a b) (q : Expression b c) (R : Attribute a) (Q : Attribute b) (hp : Controlled p) (hq : AttrSafe q Q) (hm : Q.Mono) (h : ∀ {n : ℕ} (O : IndependenceOracle n) S x,R S x → ∀ y,run O p x=some y → Q S y) : AttrSafe (p >>> q) R := attrSafe_compose p q R Q (attrSafe_controlled p hp R) hq hm h lemma attrSafe_branch {a b : DataType} (p q : Expression a b) (R : Attribute a) (hp : AttrSafe p R) (hq : AttrSafe q R) : AttrSafe (branch p q) (fun S x => R S x.2) := by obtain ⟨f,hf⟩ := hp obtain ⟨g,hg⟩ := hq refine ⟨.add .input (.add f g),fun O S z hz => ?_⟩ obtain ⟨v,x⟩ := z have hw : width x≤S := (width_snd (a:=.bool) (b:=a) (v,x)).trans hz.1 have hpf := safe_mono p x (hf O S x ⟨hw,hz.2⟩) (show f.eval S≤S+(f.eval S+g.eval S) by omega) have hqf := safe_mono q x (hg O S x ⟨hw,hz.2⟩) (show g.eval S≤S+(f.eval S+g.eval S) by omega) refine ⟨hz.1.trans (Nat.le_add_right _ _),?_,?_⟩ · intro y hy cases v · exact safe_output hpf hy · exact safe_output hqf hy · cases v · exact hpf · exact hqf lemma attrSafe_applyIf {a b : DataType} (t : Expression a .bool) (p q : Expression a b) (R : Attribute a) (hm : R.Mono) (ht : AttrSafe t R) (hp : AttrSafe p R) (hq : AttrSafe q R) : AttrSafe (applyIf t p q) R := by unfold applyIf apply attrSafe_compose _ _ R (fun S (z : Value (.prod .bool a)) => R S z.2) (attrSafe_both t ident R ht (attrSafe_controlled ident (by cc) R)) (attrSafe_branch p q R hp hq) · intro S T h z hz; exact hm S T h z.2 hz · intro n O S x hx z hz have he : x=z.2 := Option.some.inj (run_both_parts O t ident x z hz).2 exact he ▸ hx namespace Effect abbrev EffectSafe {a b : DataType} (p : Effect a b) (R : Attribute a) := AttrSafe p (fun S x => R S x.1) lemma attr_pure {a b : DataType} (p : Expression a b) (R : Attribute a) (hm : R.Mono) (hp : AttrSafe p R) : EffectSafe (pure p) R := by unfold pure apply attrSafe_both · apply attrSafe_both · exact attrSafe_controlled _ (by cc) _ · apply attrSafe_pull _ p _ R (by cc) hp hm intro n O S x hx y hy cases hy; exact hx · exact attrSafe_controlled _ (by cc) _ lemma attr_precompose {a b c : DataType} (p : Expression a b) (q : Effect b c) (R : Attribute a) (Q : Attribute b) (hp : AttrSafe p R) (hq : EffectSafe q Q) (hmR : R.Mono) (hmQ : Q.Mono) (h : ∀ {n : ℕ} (O : IndependenceOracle n) S x,R S x → ∀ y,run O p x=some y → Q S y) : EffectSafe (precompose p q) R := by unfold precompose onLeft apply attrSafe_compose _ q _ _ ?_ hq · intro S T h z hz; exact hmQ S T h z.1 hz · intro n O S x hx y hy exact h O S x.1 hx y.1 (run_both_parts O _ _ x y hy).1 · apply attrSafe_both · apply attrSafe_pull _ p _ R (by cc) hp hmR intro n O S x hx y hy cases hy; exact hx · exact attrSafe_controlled _ (by cc) _ lemma attr_keep {a b : DataType} (p : Effect a b) (R : Attribute a) (hp : EffectSafe p R) : EffectSafe (keep p) R := by unfold keep Expression.letIn apply attrSafe_post · exact attrSafe_both _ _ _ (attrSafe_controlled _ (by cc) _) hp · cc lemma attr_bind {a b c : DataType} (p : Effect a b) (q : Effect b c) (R : Attribute a) (Q : Attribute b) (hmQ : Q.Mono) (hp : EffectSafe p R) (hq : EffectSafe q Q) (h : ∀ {n : ℕ} (O : IndependenceOracle n) S x bank,R S x → ∀ y rest, run O p (x,bank)=some ((true,y),rest) → Q S y) : EffectSafe (bind p q) R := by let T : Attribute (.prod (Optional b) BankData) := fun S z => z.1.1=true → Q S z.1.2 have hmT : T.Mono := by intro S U h z hz hf; exact hmQ S U h z.1.2 (hz hf) have hq' : AttrSafe (applyIf (fst >>> fst) (both (constant (optionalValue c none)) snd) (both (fst >>> snd) snd >>> q)) T := by apply (show OracleSafe _ (fun _ _ S x => width x≤S ∧ T S x) from ?_) apply oracleSafe_applyIf _ _ _ (fun _ _ S x => width x≤S ∧ T S x) · exact oracleSafe_controlled _ (by cc) _ .input (by intro n O S x hx; exact hx.1) · exact oracleSafe_controlled _ (by cc) _ .input (by intro n O S x hx; exact hx.1.1) · apply oracleSafe_pull _ q _ (fun _ _ S x => width x≤S ∧ Q S x.1) (by cc) (.mul (.constant 2) .input) (by intro n O S x hx; exact hx.1.1.trans (by dsimp [SizePolynomial.eval]; omega)) · exact oracleSafe_lift q _ hq · intro n O S x hx y hy have hv : x.1.1=true := Option.some.inj hx.2 cases hy refine ⟨?_,hx.1.2 hv⟩ have hb := width_fst (a:=Optional b) (b:=BankData) x have hs := width_snd (a:=.bool) (b:=b) x.1 rw [width_pair (a:=b) (b:=BankData)] have hi := hx.1.1 rw [width_pair (a:=Optional b) (b:=BankData),width_pair (a:=.bool) (b:=b),width_bool] at hi omega unfold bind apply attrSafe_compose p _ _ T hp hq' hmT intro n O S x hx z hz hv obtain ⟨⟨flag,y⟩,rest⟩ := z dsimp only [Prod.fst] at hv subst flag exact h O S x.1 x.2 hx y rest hz lemma attr_letIn {a b c : DataType} (p : Effect a b) (q : Effect (.prod a b) c) (R : Attribute a) (Q : Attribute (.prod a b)) (hmQ : Q.Mono) (hp : EffectSafe p R) (hq : EffectSafe q Q) (h : ∀ S x y,R S x → Q S (x,y)) : EffectSafe (letIn p q) R := by apply attr_bind (keep p) q R Q hmQ (attr_keep p R hp) hq intro n O S x bank hx z rest hz obtain ⟨x',y⟩ := z have he := (run_keep_some O p x bank x' y rest hz).1 subst x' exact h S x y hx lemma attr_controlled {a b : DataType} (p : Effect a b) (hp : Controlled p) (R : Attribute a) : EffectSafe p R := attrSafe_controlled p hp _ lemma attr_choose {a b : DataType} (t : Expression a .bool) (p q : Effect a b) (R : Attribute a) (hm : R.Mono) (ht : Controlled t) (hp : EffectSafe p R) (hq : EffectSafe q R) : EffectSafe (choose t p q) R := by apply attrSafe_applyIf _ _ _ (fun S (x : Value (.prod a BankData)) => R S x.1) (fun S T h x hx => hm S T h x.1 hx) _ hp hq exact attrSafe_controlled _ (by cc) _ lemma attr_letControlled {a b c : DataType} (p : Effect a b) (q : Effect (.prod a b) c) (R : Attribute a) (hp : EffectSafe p R) (hq : Controlled q) : EffectSafe (letIn p q) R := attr_letIn p q R (fun _ _ => True) (by unfold Attribute.Mono; intros; trivial) hp (attr_controlled q hq _) (by intros; trivial) lemma attr_mapControlled {a b c : DataType} (p : Effect a b) (q : Expression b c) (R : Attribute a) (hp : EffectSafe p R) (hq : Controlled q) : EffectSafe (map p q) R := attr_bind p (pure q) R (fun _ _ => True) (by unfold Attribute.Mono; intros; trivial) hp (attr_controlled _ (controlled_pure q hq) _) (by intros; trivial) lemma attr_preControlled {a b c : DataType} (p : Expression a b) (q : Effect b c) (R : Attribute a) (hm : R.Mono) (hp : AttrSafe p R) (hq : Controlled q) : EffectSafe (precompose p q) R := attr_precompose p q R (fun _ _ => True) hp (attr_controlled q hq _) hm (by unfold Attribute.Mono; intros; trivial) (by intros; trivial) lemma attr_withContext {a b c : DataType} (p : Effect (.prod c a) b) (R : Attribute (.prod c a)) (hp : EffectSafe p R) : EffectSafe (withContext p) R := by unfold withContext exact attr_letControlled _ _ R hp (by ec) lemma attr_retainOption {a b : DataType} (p : Effect a (Optional b)) (R : Attribute a) (hp : EffectSafe p R) : EffectSafe (retainOption p) R := by unfold retainOption exact attr_letControlled _ _ R hp (by ec) lemma attr_some {a b : DataType} (p : Effect a b) (R : Attribute a) (hp : EffectSafe p R) : EffectSafe (someCode p) R := by unfold someCode exact attr_mapControlled _ _ R hp (by cc) lemma oracleSafe_loopStep {a : DataType} (p : Effect a a) (R : OraclePredicate a) (hp : OracleSafe p (bankScope R)) (g : SizePolynomial) : OracleSafe (loopStep p) (fun n O S x => width x≤g.eval S ∧ (x.1.1=true → R n O S x.1.2 ∧ width (a:=BankData) x.2≤S)) := by unfold loopStep apply oracleSafe_applyIf · exact oracleSafe_controlled _ (by cc) _ g (by intro n O S x hx; exact hx.1) · exact oracleSafe_controlled _ (by cc) _ g (by intro n O S x hx; exact hx.1.1) · apply oracleSafe_pull _ p _ (bankScope R) (by cc) g (by intro n O S x hx; exact hx.1.1) hp intro n O S x hx y hy have hv : x.1.1=true := Option.some.inj hx.2 cases hy exact hx.1.2 hv lemma oracleSafe_repeat_scoped {a : DataType} (p : Effect a a) (R : OraclePredicate (.prod .nat a)) (Q : OraclePredicate a) (hp : OracleSafe p (bankScope Q)) (g : SizePolynomial) (hinput : ∀ n O S k x,R n O S (k,x) → k+width (a:=a) x≤g.eval S) (hprefix : ∀ n O S k x bank,R n O S (k,x) → width (a:=BankData) bank≤S → ∀ j,j≤k → ∀ y,iterateM (run O (loopStep p)) j (optionalValue a (some x),bank)=some y → width (a:=.prod (Optional a) BankData) y≤g.eval S ∧ (y.1.1=true → Q n O S y.1.2 ∧ width (a:=BankData) y.2≤S)) : OracleSafe (repeatCode p) (bankScope R) := by let T : OraclePredicate (.prod .nat (.prod (Optional a) BankData)) := fun n O S z => ∃ k x bank,R n O S (k,x) ∧ width (a:=BankData) bank≤S ∧ z=(k,(optionalValue a (some x),bank)) let W : SizePolynomial := .add (.mul (.constant 20) g) (.add (.mul (.constant 2) .input) (.constant 20)) have htwidth : ∀ n O S x,bankScope R n O S x → width x≤W.eval S := by intro n O S x hx obtain ⟨⟨k,z⟩,bank⟩ := x have hi : k+width (a:=a) z≤g.eval S := hinput n O S k z hx.1 have h₁ := Nat.mul_le_mul_left 4 hi have hb : width (a:=BankData) bank≤S := hx.2 have hk := bits_length_le_value k rw [width_pair (a:=.prod .nat a) (b:=BankData),width_pair (a:=.nat) (b:=a),width_nat] dsimp [W,SizePolynomial.eval] omega unfold repeatCode apply oracleSafe_pull _ _ (bankScope R) T (by cc) W htwidth · apply oracleSafe_iterateNat _ T _ (oracleSafe_loopStep p Q hp g) W · intro n O S k z hz obtain ⟨k',x,bank,hx,hb,he⟩ := hz cases he have hi : k+width (a:=a) x≤g.eval S := hinput n O S k x hx have h₁ := Nat.mul_le_mul_left 2 hi rw [width_pair (a:=Optional a) (b:=BankData),width_pair (a:=.bool) (b:=a),width_bool] change k+(2*(2*1+1+width (a:=a) x)+1+width (a:=BankData) bank)≤_ have harith : ∀ (k v b G S : ℕ),k+v≤G → b≤S → k+(2*(2*1+1+v)+1+b)≤20*G+(2*S+20) := by intros; omega exact harith k (width (a:=a) x) (width (a:=BankData) bank) (g.eval S) S hi hb · intro n O S k z hz j hj y hy obtain ⟨k',x,bank,hx,hb,he⟩ := hz cases he have hh := (hprefix n O S k x bank hx hb j hj y hy).1 dsimp [W,SizePolynomial.eval] omega · intro n O S k z hz j hj y hy obtain ⟨k',x,bank,hx,hb,he⟩ := hz cases he exact hprefix n O S k x bank hx hb j hj.le y hy · intro n O S x hx y hy cases hy exact ⟨x.1.1,x.1.2,x.2,hx.1,hx.2,rfl⟩ lemma oracleSafe_repeat_law {a : DataType} (p : Effect a a) (R : OraclePredicate (.prod .nat a)) (Q : OraclePredicate a) (hp : OracleSafe p (bankScope Q)) (g : SizePolynomial) (hinput : ∀ n O S k x,R n O S (k,x) → k+width (a:=a) x≤g.eval S) (hlaw : ∀ n O S k x,R n O S (k,x) → ∀ j,j≤k → ∃ (A : Type) (e : A → Value a) (t : DrawTree A), RealizesLaw O (repeatCode p) e (j,x) t ∧ DrawTree.All (fun v => width (e v)≤g.eval S ∧ Q n O S (e v)) t) : OracleSafe (repeatCode p) (bankScope R) := by let W : SizePolynomial := .add (.mul (.constant 2) g) (.add .input (.constant (2*(width (zeroValue a)+3)+1))) apply oracleSafe_repeat_scoped p R Q hp W · intro n O S k x hx have hh : k+width (a:=a) x≤g.eval S := hinput n O S k x hx exact hh.trans (by omega : g.eval S≤2*g.eval S+(S+(2*(width (zeroValue a)+3)+1))) · intro n O S k x bank hx hb j hj y hy obtain ⟨A,e,t,ht,he⟩ := hlaw n O S k x hx j hj have hyr : run O (repeatCode p) ((j,x),bank)=some y := by rw [run_repeat]; exact hy have hh := ht.run_bound (g.eval S) (Q n O S) he bank y hyr have hr := ht.rest_width bank y hyr refine ⟨?_,fun hv => ⟨hh.2 hv,hr.trans hb⟩⟩ dsimp [W,SizePolynomial.eval] omega lemma oracleSafe_mapControlled {a b c : DataType} (p : Effect a b) (q : Expression b c) (R : OraclePredicate (.prod a BankData)) (hp : OracleSafe p R) (hq : Controlled q) : OracleSafe (map p q) R := by unfold map bind apply oracleSafe_post _ _ R hp have hh := controlled_pure q hq cc lemma oracleSafe_letControlled {a b c : DataType} (p : Effect a b) (q : Effect (.prod a b) c) (R : OraclePredicate (.prod a BankData)) (hp : OracleSafe p R) (hq : Controlled q) : OracleSafe (letIn p q) R := by unfold letIn bind apply oracleSafe_post _ _ R (oracleSafe_keep p R hp) cc lemma oracleSafe_withContext {a b c : DataType} (p : Effect (.prod c a) b) (R : OraclePredicate (.prod (.prod c a) BankData)) (hp : OracleSafe p R) : OracleSafe (withContext p) R := by unfold withContext exact oracleSafe_letControlled _ _ R hp (by ec) lemma oracleSafe_retainOption {a b : DataType} (p : Effect a (Optional b)) (R : OraclePredicate (.prod a BankData)) (hp : OracleSafe p R) : OracleSafe (retainOption p) R := by unfold retainOption exact oracleSafe_letControlled _ _ R hp (by ec) lemma oracleSafe_withOptionContext {a b c : DataType} (p : Effect (.prod c a) (Optional b)) (R : OraclePredicate (.prod (.prod c a) BankData)) (hp : OracleSafe p R) : OracleSafe (withOptionContext p) R := by unfold withOptionContext exact oracleSafe_letControlled _ _ R hp (by ec) end Effect lemma oracleSafe_attr {a b : DataType} (p : Expression a b) (A : Attribute a) (hA : A.Mono) (hp : AttrSafe p A) (R : OraclePredicate a) (g : SizePolynomial) (hw : ∀ n O S x,R n O S x → width x≤g.eval S) (ha : ∀ n O S x,R n O S x → A S x) : OracleSafe p R := by let W : SizePolynomial := .add g .input apply oracleSafe_mono p (oracleSafe_reparam p _ (oracleSafe_lift p _ hp) W) intro n O S x hx exact ⟨(hw n O S x hx).trans (Nat.le_add_right _ _), hA S _ (Nat.le_add_left _ _) x (ha n O S x hx)⟩ namespace Effect lemma oracleSafe_effectAttr {a b : DataType} (p : Effect a b) (A : Attribute a) (hA : A.Mono) (hp : EffectSafe p A) (R : OraclePredicate a) (g : SizePolynomial) (hw : ∀ n O S x,R n O S x → width x≤g.eval S) (ha : ∀ n O S x,R n O S x → A S x) : OracleSafe p (bankScope R) := by apply oracleSafe_attr p (fun S x => A S x.1) (fun S T h x hx => hA S T h x.1 hx) hp _ (.add (.mul (.constant 2) g) (.add .input (.constant 1))) · intro n O S x hx have hw' := hw n O S x.1 hx.1 have hb := hx.2 rw [width_pair (a:=a) (b:=BankData)] dsimp [SizePolynomial.eval] omega · intro n O S x hx; exact ha n O S x.1 hx.1 lemma oracleSafe_choose {a b : DataType} (test : Expression a .bool) (p q : Effect a b) (R : OraclePredicate (.prod a BankData)) (ht : Controlled test) (hp : OracleSafe p R) (hq : OracleSafe q R) : OracleSafe (choose test p q) R := by obtain ⟨f,hf⟩ := oracleSafe_input_bound p R hp apply oracleSafe_applyIf _ _ _ R · exact oracleSafe_controlled _ (by cc) R f hf · exact oracleSafe_mono p hp (by intro n O S x hx; exact hx.1) · exact oracleSafe_mono q hq (by intro n O S x hx; exact hx.1) lemma oracleSafe_letIn {a b c : DataType} (p : Effect a b) (q : Effect (.prod a b) c) (R : OraclePredicate a) (Q : OraclePredicate (.prod a b)) (hp : OracleSafe p (bankScope R)) (hq : OracleSafe q (bankScope Q)) (h : ∀ n O S x bank,R n O S x → width (a:=BankData) bank≤S → ∀ y rest, run O p (x,bank)=some ((true,y),rest) → Q n O S (x,y) ∧ width (a:=BankData) rest≤S) : OracleSafe (letIn p q) (bankScope R) := by apply oracleSafe_bind (keep p) q R Q (oracleSafe_keep p _ hp) hq intro n O S x bank hx hb z rest hz obtain ⟨x',y⟩ := z have he := run_keep_some O p x bank x' y rest hz rw [he.1] exact h n O S x bank hx hb y rest he.2 def optionScope {a : DataType} (R : OraclePredicate a) : OraclePredicate (Optional a) := fun n O S x => x=optionalValue a none ∨ x.1=true ∧ R n O S x.2 lemma optionScope_encode {A : Type*} {a : DataType} (R : OraclePredicate a) {n : ℕ} (O : IndependenceOracle n) (S : ℕ) (e : A → Value a) (he : ∀ z,R n O S (e z)) (v : Option A) : optionScope R n O S (optionEncode e v) := by cases v with | none => exact Or.inl rfl | some z => exact Or.inr ⟨rfl,he z⟩ lemma optionScope_width {a : DataType} (R : OraclePredicate a) (g : SizePolynomial) (hw : ∀ n O S x,R n O S x → width x≤g.eval S) : ∀ n O S x,optionScope R n O S x → width x≤ (.add g (.constant (width (zeroValue a)+3)) : SizePolynomial).eval S := by intro n O S x hx rcases hx with rfl | ⟨hflag,hx⟩ · rw [width_pair (a:=.bool) (b:=a),width_bool] change 2*1+1+width (zeroValue a)≤_ dsimp [SizePolynomial.eval] omega · have hh := hw n O S x.2 hx rw [width_pair (a:=.bool) (b:=a),width_bool] dsimp [SizePolynomial.eval] omega lemma oracleSafe_optionContinue {a b : DataType} (p : Effect a (Optional b)) (R : OraclePredicate a) (hp : OracleSafe p (bankScope R)) : OracleSafe (optionContinue p) (bankScope (optionScope R)) := by obtain ⟨f,hf⟩ := oracleSafe_input_bound p (bankScope R) hp have hu : ∀ n O S x,R n O S x → width (a:=a) x≤f.eval S := by intro n O S x hx exact (width_fst (a:=a) (b:=BankData) (x,([] : Bank))).trans (hf n O S (x,[]) ⟨hx,by exact Nat.zero_le S⟩) let W : SizePolynomial := .add (.mul (.constant 2) (.add f (.constant (width (zeroValue a)+3)))) (.add .input (.constant 1)) have hw : ∀ n O S x,bankScope (optionScope R) n O S x → width x≤W.eval S := by intro n O S x hx have hh := optionScope_width R f hu n O S x.1 hx.1 have hb := hx.2 rw [width_pair (a:=Optional a) (b:=BankData)] dsimp [W,SizePolynomial.eval] at * omega unfold optionContinue choose apply oracleSafe_applyIf _ _ _ _ · exact oracleSafe_controlled _ (by cc) _ W hw · exact oracleSafe_controlled _ (by ec) _ W (by intro n O S x hx; exact hw n O S x hx.1) · unfold precompose onLeft apply oracleSafe_pull _ p _ (bankScope R) (by cc) W (by intro n O S x hx; exact hw n O S x hx.1) hp intro n O S x hx y hy have hv : x.1.1=true := Option.some.inj hx.2 have he : (x.1.2,x.2)=y := Option.some.inj hy subst y refine ⟨?_,hx.1.2⟩ rcases hx.1.1 with hnone | ⟨_,hh⟩ · rw [hnone] at hv; cases hv · exact hh lemma oracleSafe_optionBind {a b c : DataType} (p : Effect a (Optional b)) (q : Effect b (Optional c)) (R : OraclePredicate a) (Q : OraclePredicate b) (hp : OracleSafe p (bankScope R)) (hq : OracleSafe q (bankScope Q)) (h : ∀ n O S x bank,R n O S x → width (a:=BankData) bank≤S → ∀ y rest, run O p (x,bank)=some ((true,y),rest) → optionScope Q n O S y ∧ width (a:=BankData) rest≤S) : OracleSafe (optionBind p q) (bankScope R) := oracleSafe_bind p _ R _ hp (oracleSafe_optionContinue q Q hq) h end Effect def contextAttr (S : ℕ) (x : Value WeightContext) : Prop := x.1.1≤S ∧ x.1.2≤S def weightAttr (S : ℕ) (x : Value WeightInput) : Prop := contextAttr S x.1 lemma contextAttr_mono : Attribute.Mono (a:=WeightContext) contextAttr := by intro S T h x hx; exact ⟨hx.1.trans h,hx.2.trans h⟩ lemma weightAttr_mono : Attribute.Mono (a:=WeightInput) weightAttr := by intro S T h x hx; exact contextAttr_mono S T h x.1 hx lemma attr_weight : AttrSafe weightCode weightAttr := polySafe_mono weightCode polySafe_weight (by intro S x hx; exact ⟨hx.1,hx.2.1,hx.2.2⟩) def acceptanceAttr (S : ℕ) (x : Value AcceptanceInput) : Prop := contextAttr S x.1 lemma acceptanceAttr_mono : Attribute.Mono (a:=AcceptanceInput) acceptanceAttr := by intro S T h x hx; exact contextAttr_mono S T h x.1 hx lemma attr_acceptance : AttrSafe acceptanceCode acceptanceAttr := by unfold acceptanceCode apply attrSafe_post · apply attrSafe_both · apply attrSafe_pull _ weightCode acceptanceAttr weightAttr (by cc) attr_weight weightAttr_mono intro n O S x hx y hy cases hy exact hx · apply attrSafe_pull _ weightCode acceptanceAttr weightAttr (by cc) attr_weight weightAttr_mono intro n O S x hx y hy cases hy exact hx · cc namespace Effect def offerAttr (S : ℕ) (x : Value OfferInput) : Prop := weightAttr S x.1 lemma offerAttr_mono : Attribute.Mono (a:=OfferInput) offerAttr := by intro S T h x hx; exact weightAttr_mono S T h x.1 hx lemma attr_offerCore : EffectSafe offerCore offerAttr := by unfold offerCore apply attr_choose _ _ _ offerAttr offerAttr_mono (by have h := controlled_chainCode; cc) · exact attr_controlled _ (by ec) _ · apply attr_letControlled · apply attr_preControlled _ bernoulliCode offerAttr offerAttr_mono _ controlled_bernoulli apply attrSafe_pull acceptancePrep acceptanceCode offerAttr acceptanceAttr (by unfold acceptancePrep; cc) attr_acceptance acceptanceAttr_mono intro n O S x hx y hy cases hy exact hx · ec def pairOfferAttr (S : ℕ) (x : Value (.prod WeightInput NN)) : Prop := weightAttr S x.1 lemma pairOfferAttr_mono : Attribute.Mono (a:=(.prod WeightInput NN)) pairOfferAttr := by intro S T h x hx; exact weightAttr_mono S T h x.1 hx lemma attr_offer : EffectSafe offerCode pairOfferAttr := by have he := controlled_exchangeSet unfold offerCode apply attr_precompose _ _ pairOfferAttr offerAttr (attrSafe_controlled _ (by cc) _) attr_offerCore pairOfferAttr_mono offerAttr_mono intro n O S x hx y hy have hh : x.1=y.1 := Option.some.inj (run_both_parts O _ _ x y hy).1 change weightAttr S y.1 rw [←hh] exact hx lemma attr_activeStep : EffectSafe activeStepCode weightAttr := by unfold activeStepCode apply attr_letIn _ _ weightAttr pairOfferAttr pairOfferAttr_mono (attr_controlled _ (by have h := controlled_proposal; ec) _) attr_offer intro S x y hx exact hx lemma attr_step : EffectSafe stepCode weightAttr := by unfold stepCode apply attr_letIn _ _ weightAttr (fun S x => weightAttr S x.1) (fun S T h (x : Value (.prod WeightInput .bool)) hx => weightAttr_mono S T h x.1 hx) (attr_controlled _ (by have h := controlled_bernoulli; ec) _) · apply attr_choose _ _ _ _ (fun S T h (x : Value (.prod WeightInput .bool)) hx => weightAttr_mono S T h x.1 hx) (by cc) · apply attr_precompose _ _ _ weightAttr (attrSafe_controlled _ (by cc) _) attr_activeStep (fun S T h (x : Value (.prod WeightInput .bool)) hx => weightAttr_mono S T h x.1 hx) weightAttr_mono intro n O S x hx y hy cases hy; exact hx · exact attr_controlled _ (by ec) _ · intro S x y hx; exact hx end Effect open scoped Classical lemma width_stateEncode {n : ℕ} (T : Set (Fin n⊕Fin n)) : width (a:=StateData) (stateEncode T)=3*n+1 := by rw [width_pair (a:=.word) (b:=.word),width_word,width_word,stateEncode_left_length,stateEncode_right_length] omega lemma width_sampleEncode {n : ℕ} (xs : List (Set (Fin n⊕Fin n))) : width (a:=SampleData) (sampleEncode xs)=xs.length*(6*n+4) := by induction xs with | nil => change width (a:=.list StateData) []=0*(6*n+4); rw [width_nil,Nat.zero_mul] | cons x xs ih => change width (a:=.list StateData) (stateEncode x::sampleEncode xs)=_ rw [width_cons (a:=StateData),width_stateEncode,ih,List.length_cons,Nat.add_mul,Nat.one_mul] omega lemma width_observation {n N : ℕ} (v : PhaseSample n N) : width (a:=SampleData) (sampleEncode (observedSets n N v))≤(N+1)*(6*n+4) := by rw [width_sampleEncode] have hl : (observedSets n N v).length=N-1+1 := by simp only [observedSets,List.length_map] exact FiniteChain.Sample.toList_length v rw [hl] exact Nat.mul_le_mul_right _ (by omega) lemma width_history_observed {n N : ℕ} (h : List (PhaseSample n N)) : width (a:=HistoryData) (historyEncode (h.map (observedSets n N)))≤h.length*(2*((N+1)*(6*n+4))+2) := by unfold historyEncode apply (width_list_le _ _ ?_).trans · simp only [List.length_map]; rfl · intro x hx obtain ⟨v,hv,rfl⟩ := List.mem_map.mp hx obtain ⟨u,hu,rfl⟩ := List.mem_map.mp hv exact width_observation u open Expression open Effect open scoped Classical structure SamplerModel (n : ℕ) (O : IndependenceOracle n) where M₁ : Matroid (Fin n) M₂ : Matroid (Fin n) exact : ExactOracles M₁ M₂ O ground₁ : M₁.E=Set.univ ground₂ : M₂.E=Set.univ positive : 0 ∃ (m : SamplerModel n O),m.Bounded S ∧ ∃ h : m.Hist,h.length≤S ∧ ∃ j,j≤S ∧ ∃ x : ChainIndex (pairedSlots n),z=m.weightValue h j x lemma weightScope_width : ∀ n O S z,weightScope n O S z → width z≤(sourceWidthPoly 100).eval S := by intro n O S z hz obtain ⟨m,hm,h,hh,j,hj,x,rfl⟩ := hz rw [eval_sourceWidthPoly] exact m.width_weightValue S hm h hh j hj x namespace Effect lemma safe_step : OracleSafe stepCode (bankScope weightScope) := by apply oracleSafe_effectAttr stepCode weightAttr weightAttr_mono attr_step weightScope (sourceWidthPoly 100) weightScope_width intro n O S z hz obtain ⟨m,hm,h,hh,j,hj,x,rfl⟩ := hz exact ⟨hm.2.1,hj⟩ lemma attr_storedStep : EffectSafe storedStepCode weightAttr := by unfold storedStepCode apply attr_precompose storedStepPrep stepCode weightAttr weightAttr (attrSafe_controlled _ (by unfold storedStepPrep; cc) _) attr_step weightAttr_mono weightAttr_mono intro n O S x hx y hy unfold storedStepPrep at hy have he := run_both_parts O _ _ x y hy have hc := run_both_parts O _ _ x y.1 he.1 have hp : x.1.1=y.1.1 := Option.some.inj hc.1 change x.1.1.1≤S ∧ x.1.1.2≤S at hx change y.1.1.1≤S ∧ y.1.1.2≤S rw [←hp]; exact hx lemma safe_storedStep : OracleSafe storedStepCode (bankScope weightScope) := by apply oracleSafe_effectAttr storedStepCode weightAttr weightAttr_mono attr_storedStep weightScope (sourceWidthPoly 100) weightScope_width intro n O S z hz obtain ⟨m,hm,h,hh,j,hj,x,rfl⟩ := hz exact ⟨hm.2.1,hj⟩ end Effect end MachineCode namespace DrawTree lemma all_of_forall {A : Type*} (t : DrawTree A) (P : A → Prop) (h : ∀ x,P x) : All P t := by induction t with | leaf x => exact h x | draw n k ih => exact ih end DrawTree namespace MachineCode open Expression open scoped Classical namespace Effect lemma oracleSafe_hitStep {a : DataType} (step : Effect a a) (test : Expression a .bool) (Q : OraclePredicate a) (hs : OracleSafe step (bankScope Q)) (ht : Controlled test) (g : SizePolynomial) (hw : ∀ n O S x,Q n O S x → width x≤g.eval S) : OracleSafe (hitStepCode step test) (bankScope (fun n O S x => Q n O S x.1)) := by let W : SizePolynomial := .add (.mul (.constant 2) g) (.constant 2) have hw' : ∀ n O S x,Q n O S x.1 → width (a:=.prod a .bool) x≤W.eval S := by intro n O S x hx have hh := hw n O S x.1 hx rw [width_pair (a:=a) (b:=.bool),width_bool] dsimp [W,SizePolynomial.eval] omega unfold hitStepCode apply oracleSafe_choose _ _ _ _ (by cc) · apply oracleSafe_mapControlled _ _ _ _ (by cc) exact oracleSafe_precompose fst step _ Q (oracleSafe_controlled _ (by cc) _ W hw') hs (by intro n O S x hx y hy; cases hy; exact hx) · exact oracleSafe_pure ident _ (oracleSafe_controlled _ (by cc) _ W hw') abbrev SearchData := DataType.prod WeightInput .bool def searchScope : OraclePredicate SearchData := fun n O S x => weightScope n O S x.1 def searchInputScope : OraclePredicate (.prod .nat SearchData) := fun n O S x => x.1≤S+1 ∧ ∃ (m : SamplerModel n O),m.Bounded S ∧ ∃ h : m.Hist,h.length≤S ∧ ∃ j,j≤S ∧ ∃ u : SearchState (ChainIndex (pairedSlots n)) (plainPredicate (pairedSlots n)), x.2=searchEncode (m.weightValue h j) u lemma searchScope_width : ∀ n O S x,searchScope n O S x → width x≤(sourceWidthPoly 202).eval S := by intro n O S x hx have hh := weightScope_width n O S x.1 hx rw [eval_sourceWidthPoly] at hh ⊢ rw [width_pair (a:=WeightInput) (b:=.bool),width_bool] have hp : 1≤(S+1)^3 := (Nat.succ_le_succ (Nat.zero_le S)).trans (Nat.le_self_pow (by decide) _) omega lemma searchEncode_scope {n : ℕ} {O : IndependenceOracle n} (m : SamplerModel n O) (S : ℕ) (hm : m.Bounded S) (h : m.Hist) (hh : h.length≤S) (j : ℕ) (hj : j≤S) (u : SearchState (ChainIndex (pairedSlots n)) (plainPredicate (pairedSlots n))) : searchScope n O S (searchEncode (m.weightValue h j) u) := by cases u with | inl x => exact ⟨m,hm,h,hh,j,hj,x,rfl⟩ | inr x => exact ⟨m,hm,h,hh,j,hj,x.val,rfl⟩ lemma safe_repeatHit : OracleSafe (repeatCode (hitStepCode (withContext storedStepCode) (snd >>> Expression.plainCode))) (bankScope searchInputScope) := by have hs : OracleSafe (withContext storedStepCode) (bankScope weightScope) := oracleSafe_withContext storedStepCode _ safe_storedStep apply oracleSafe_repeat_law _ searchInputScope searchScope (oracleSafe_hitStep _ _ weightScope hs (by cc) _ weightScope_width) (sourceWidthPoly 204) · intro n O S k x hx obtain ⟨hk,m,hm,h,hh,j,hj,u,rfl⟩ := hx have hw := searchScope_width n O S _ (searchEncode_scope m S hm h hh j hj u) rw [eval_sourceWidthPoly] at hw ⊢ have hp : S+1≤(S+1)^3 := Nat.le_self_pow (by decide) _ have harith : ∀ (k v T P : ℕ), k≤T → T≤P → v≤202*P → k+v≤204*P := by intros; omega exact harith k _ (S+1) _ hk hp hw · intro n O S k x hx l hl obtain ⟨hk,m,hm,h,hh,j,hj,u,rfl⟩ := hx let f := canonicalStepTree n m.positive m.rank O m.samples h j let e := m.weightValue h j let P := plainPredicate (pairedSlots n) refine ⟨SearchState (ChainIndex (pairedSlots n)) P,searchEncode e, treeRepeat (searchStep f P) l u,?_,?_⟩ · apply law_repeat O _ _ _ _ l u exact law_hitStep O (withContext storedStepCode) _ e f P (fun T => law_withContext O storedStepCode _ (m.weightContext h j) _ _ (storedStepCode_source m.M₁ m.M₂ O m.exact m.ground₁ m.ground₂ m.rank m.samples h j m.positive T)) (fun T => MachineCode.plainCode_source O T.val) · apply DrawTree.all_of_forall intro v have hv := searchEncode_scope m S hm h hh j hj v refine ⟨?_,hv⟩ have hw := searchScope_width n O S _ hv rw [eval_sourceWidthPoly] at hw ⊢ exact hw.trans (Nat.mul_le_mul_right _ (by decide : 202≤204)) def traceScope : OraclePredicate (.prod .nat WeightInput) := fun n O S x => x.1≤S+1 ∧ weightScope n O S x.2 lemma traceScope_width : ∀ n O S x,traceScope n O S x → width x≤(sourceWidthPoly 110).eval S := by intro n O S x hx have hk := (bits_length_le_value x.1).trans hx.1 have hh := weightScope_width n O S x.2 hx.2 rw [eval_sourceWidthPoly] at hh ⊢ rw [width_pair (a:=.nat) (b:=WeightInput),width_nat] have hp : S+1≤(S+1)^3 := Nat.le_self_pow (by decide) _ omega lemma safe_trace : OracleSafe traceCode (bankScope traceScope) := by unfold traceCode apply oracleSafe_mapControlled _ _ _ _ (by cc) unfold hittingCode apply oracleSafe_precompose _ _ traceScope searchInputScope (oracleSafe_controlled _ (by cc) _ _ traceScope_width) (oracleSafe_mapControlled _ _ _ safe_repeatHit (by unfold hitFinish; cc)) intro n O S x hx y hy have he : (x.1,(x.2,false))=y := Option.some.inj hy subst y obtain ⟨m,hm,h,hh,j,hj,T,he⟩ := hx.2 exact ⟨hx.1,m,hm,h,hh,j,hj,Sum.inl T,by rw [he]; rfl⟩ end Effect open Expression lemma attr_rangeCode : AttrSafe rangeCode (fun S k => k≤S) := polySafe_mono rangeCode polySafe_rangeCode (by intro S k hk; exact hk.2) lemma attr_powCode : AttrSafe powCode (fun S x => x.2≤S) := by apply polySafe_mono powCode polySafe_powCode intro S x hx exact ⟨(width_fst (a:=.nat) (b:=.nat) x).trans hx.1,hx.2⟩ lemma attr_paddedBits : AttrSafe paddedBitsCode (fun S x => x.1≤S) := by unfold paddedBitsCode apply attrSafe_post · apply attrSafe_both · apply attrSafe_pull fst rangeCode _ _ (by cc) attr_rangeCode (fun S T h k hk => hk.trans h) intro n O S x hx y hy cases hy; exact hx · exact attrSafe_controlled _ (by cc) _ · cc lemma attr_plainDecode : AttrSafe plainDecodeCode (fun S x => x.1≤S) := by unfold plainDecodeCode exact attrSafe_post _ _ _ attr_paddedBits (by cc) namespace Effect lemma attr_plain : EffectSafe plainCode (fun S x => x≤S) := by unfold plainCode apply attr_letIn (a:=.nat) (b:=.nat) (c:=StateData) _ _ (fun (S : ℕ) (x : ℕ) => x≤S) (fun (S : ℕ) (x : ℕ × ℕ) => x.1≤S) (fun S T h x hx => hx.trans h) · apply attr_preControlled _ _ _ (fun S T h x hx => hx.trans h) _ controlled_draw apply attrSafe_pull _ powCode _ _ (by cc) attr_powCode (fun S T h x hx => hx.trans h) intro n O S x hx y hy cases hy exact hx · exact attr_pure plainDecodeCode _ (fun S T h x hx => hx.trans h) attr_plainDecode · intro S x y hx exact hx lemma safe_plain : OracleSafe plainCode (bankScope (fun _ _ S x => x≤S)) := by apply oracleSafe_effectAttr plainCode _ (fun S T h x hx => hx.trans h) attr_plain _ .input · intro n O S x hx exact (bits_length_le_value x).trans hx · intros; assumption end Effect open Expression open scoped Classical namespace SamplerModel lemma Bounded.mono {n : ℕ} {O : IndependenceOracle n} {m : SamplerModel n O} {S T : ℕ} (hm : m.Bounded S) (h : S≤T) : m.Bounded T := ⟨hm.1.trans h,hm.2.1.trans h,hm.2.2.1.trans h,hm.2.2.2.1.trans h, hm.2.2.2.2.1.trans h,hm.2.2.2.2.2.trans h⟩ end SamplerModel namespace Effect def restartScope : OraclePredicate RestartState := fun n O S z => ∃ (m : SamplerModel n O),m.Bounded S ∧ ∃ h : m.Hist,h.length≤S ∧ ∃ j,j≤S ∧ ∃ x : PlainIndex (pairedSlots n),z=m.restartValue h j x lemma restartScope_width : ∀ n O S z,restartScope n O S z → width z≤(sourceWidthPoly 200).eval S := by intro n O S z hz obtain ⟨m,hm,h,hh,j,hj,x,rfl⟩ := hz rw [eval_sourceWidthPoly] exact m.width_restartValue S hm h hh j hj x lemma safe_traceAt : OracleSafe traceAtCode (bankScope restartScope) := by unfold traceAtCode apply oracleSafe_precompose traceAtPrep traceCode restartScope traceScope (oracleSafe_controlled _ (by unfold traceAtPrep; cc) _ _ restartScope_width) safe_trace intro n O S z hz y hy obtain ⟨m,hm,h,hh,j,hj,x,rfl⟩ := hz have he : (m.cap+1,m.weightValue h j x.val)=y := Option.some.inj hy subst y exact ⟨Nat.add_le_add_right hm.2.2.2.2.1 1,m,hm,h,hh,j,hj,x.val,rfl⟩ def traceRepeatScope : OraclePredicate (.prod .nat (Optional RestartState)) := fun n O S z => z.1≤S ∧ ∃ (m : SamplerModel n O),m.Bounded S ∧ ∃ h : m.Hist,h.length≤S ∧ ∃ j,j≤S ∧ ∃ x : PlainIndex (pairedSlots n),z.2=optionEncode (m.restartValue h j) (some x) def restartOptWidth : SizePolynomial := .add (sourceWidthPoly 200) (.constant (width (zeroValue RestartState)+3)) lemma restartOptWidth_bound {n : ℕ} {O : IndependenceOracle n} (m : SamplerModel n O) (S : ℕ) (hm : m.Bounded S) (h : m.Hist) (hh : h.length≤S) (j : ℕ) (hj : j≤S) (v : Option (PlainIndex (pairedSlots n))) : width (optionEncode (m.restartValue h j) v)≤restartOptWidth.eval S := by have hw := width_optionEncode (m.restartValue h j) v ((sourceWidthPoly 200).eval S) (fun x => by rw [eval_sourceWidthPoly]; exact m.width_restartValue S hm h hh j hj x) change _ ≤ (sourceWidthPoly 200).eval S + (width (zeroValue RestartState)+3) omega lemma safe_repeatTrace : OracleSafe (repeatCode (optionContinue (withOptionContext traceAtCode))) (bankScope traceRepeatScope) := by apply oracleSafe_repeat_law _ traceRepeatScope (optionScope restartScope) (oracleSafe_optionContinue _ _ (oracleSafe_withOptionContext _ _ safe_traceAt)) (.add .input restartOptWidth) · intro n O S k z hz obtain ⟨hk,m,hm,h,hh,j,hj,x,rfl⟩ := hz exact Nat.add_le_add hk (restartOptWidth_bound m S hm h hh j hj _) · intro n O S k z hz l hl obtain ⟨hk,m,hm,h,hh,j,hj,x,rfl⟩ := hz let e := m.restartValue h j let f := canonicalTraceTree n m.positive m.rank O m.samples h j m.cap let F : Option (PlainIndex (pairedSlots n)) → DrawTree (Option (PlainIndex (pairedSlots n))) := fun u => match u with | none => .leaf none | some y => f y refine ⟨Option (PlainIndex (pairedSlots n)),optionEncode e,treeRepeat F l (some x),?_,?_⟩ · apply law_repeat O _ _ F _ l (some x) intro u change RealizesLaw O (optionContinue (withOptionContext traceAtCode)) (optionEncode e) (optionEncode e u) (match u with | none => .leaf none | some y => f y) cases u <;> exact law_optionContinue O (withOptionContext traceAtCode) e e f _ (fun y => law_withOptionContext O traceAtCode (fun x : PlainIndex (pairedSlots n) => stateEncode x.val.val) (m.restartContext h,j) (stateEncode y.val.val) (f y) (traceAtCode_source m.M₁ m.M₂ O m.exact m.ground₁ m.ground₂ m.rank m.samples m.phases h m.positive m.cap j y)) · apply DrawTree.all_of_forall intro v refine ⟨(restartOptWidth_bound m S hm h hh j hj v).trans (Nat.le_add_left _ _),?_⟩ apply optionScope_encode intro y exact ⟨m,hm,h,hh,j,hj,y,rfl⟩ def iterateTraceScope : OraclePredicate (.prod .nat RestartState) := fun n O S z => z.1≤S ∧ restartScope n O S z.2 lemma iterateTraceScope_width : ∀ n O S z,iterateTraceScope n O S z → width z≤(SizePolynomial.add (.mul (.constant 2) .input) (.add (.constant 1) (sourceWidthPoly 200))).eval S := by intro n O S z hz have hk := (bits_length_le_value z.1).trans hz.1 have hh := restartScope_width n O S z.2 hz.2 rw [width_pair (a:=.nat) (b:=RestartState),width_nat] change _ ≤ 2*S+(1+(sourceWidthPoly 200).eval S) omega lemma safe_iterateTrace : OracleSafe (iterateCode (withOptionContext traceAtCode)) (bankScope iterateTraceScope) := by unfold iterateCode apply oracleSafe_precompose _ _ iterateTraceScope traceRepeatScope (oracleSafe_controlled _ (by cc) _ _ iterateTraceScope_width) safe_repeatTrace intro n O S z hz y hy have he : (z.1,(true,z.2))=y := Option.some.inj hy subst y obtain ⟨m,hm,h,hh,j,hj,x,he⟩ := hz.2 exact ⟨hz.1,m,hm,h,hh,j,hj,x,by rw [he]; rfl⟩ lemma safe_restartTick : OracleSafe restartTick (bankScope restartScope) := by unfold restartTick apply oracleSafe_precompose restartTickPrep _ restartScope (fun n O S z => iterateTraceScope n O (S+1) z) (oracleSafe_controlled _ (by unfold restartTickPrep; cc) _ _ restartScope_width) · apply oracleSafe_mono _ (oracleSafe_reparam _ _ safe_iterateTrace (.add .input (.constant 1))) intro n O S z hz exact ⟨hz.1,hz.2.trans (Nat.le_add_right S 1)⟩ · intro n O S z hz y hy obtain ⟨m,hm,h,hh,j,hj,x,rfl⟩ := hz have he : (m.tau,m.restartValue h (j+1) x)=y := Option.some.inj hy subst y exact ⟨hm.2.2.2.2.2.trans (Nat.le_add_right S 1),m,hm.mono (Nat.le_add_right S 1), h,hh.trans (Nat.le_add_right S 1),j+1,Nat.add_le_add_right hj 1,x,rfl⟩ end Effect open Expression open scoped Classical namespace SamplerModel noncomputable def restartInput {n : ℕ} {O : IndependenceOracle n} (m : SamplerModel n O) (h : m.Hist) (k : ℕ) : Value RestartInput := (n,(k,m.restartContext h)) lemma width_restartInput {n : ℕ} {O : IndependenceOracle n} (m : SamplerModel n O) (S : ℕ) (hm : m.Bounded S) (h : m.Hist) (hh : h.length≤S) (k : ℕ) (hk : k≤S) : width (m.restartInput h k)≤(sourceWidthPoly 210).eval S := by let x : PlainIndex (pairedSlots n) := Classical.choice (plainIndex_nonempty (pairedSlots n) (pairedSlots_fresh n) (pairedSlots_cover n)) have hw := m.width_restartValue S hm h hh 0 (Nat.zero_le S) x have hc : width (m.restartContext h)≤200*(S+1)^3 := (width_fst (a:=RestartContext) (b:=.nat) (m.restartContext h,0)).trans ((width_fst (a:=.prod RestartContext .nat) (b:=StateData) (m.restartValue h 0 x)).trans hw) have hn := (bits_length_le_value n).trans hm.1 have hb := (bits_length_le_value k).trans hk rw [eval_sourceWidthPoly,restartInput,width_pair (a:=.nat) (b:=.prod .nat RestartContext), width_pair (a:=.nat) (b:=RestartContext),width_nat,width_nat] have hp : S+1≤(S+1)^3 := Nat.le_self_pow (by decide) _ omega end SamplerModel namespace Effect def restartRepeatScope : OraclePredicate (.prod .nat (Optional RestartState)) := fun n O S z => z.1≤S ∧ ∃ (m : SamplerModel n O),m.Bounded S ∧ ∃ h : m.Hist,h.length≤S ∧ ∃ x : PlainIndex (pairedSlots n),z.2=optionEncode (m.restartValue h 0) (some x) lemma safe_restartRepeat : OracleSafe (repeatCode (optionContinue restartTick)) (bankScope restartRepeatScope) := by apply oracleSafe_repeat_law _ restartRepeatScope (optionScope restartScope) (oracleSafe_optionContinue _ _ safe_restartTick) (.add .input restartOptWidth) · intro n O S k z hz obtain ⟨hk,m,hm,h,hh,x,rfl⟩ := hz exact Nat.add_le_add hk (restartOptWidth_bound m S hm h hh 0 (Nat.zero_le S) _) · intro n O S k z hz j hj obtain ⟨hk,m,hm,h,hh,x,rfl⟩ := hz let f := fun l => DrawTree.iterate (canonicalTraceTree n m.positive m.rank O m.samples h l m.cap) m.tau refine ⟨Option (PlainIndex (pairedSlots n)),optionEncode (m.restartValue h j), phaseRepeat f j x,?_,?_⟩ · apply law_phaseRepeat O restartTick (m.restartValue h) f _ j x intro l y exact restartTick_source m.M₁ m.M₂ O m.exact m.ground₁ m.ground₂ m.rank m.samples m.phases h m.positive m.cap l y · apply DrawTree.all_of_forall intro v refine ⟨(restartOptWidth_bound m S hm h hh j (hj.trans hk) v).trans (Nat.le_add_left _ _),?_⟩ apply optionScope_encode intro y exact ⟨m,hm,h,hh,j,hj.trans hk,y,rfl⟩ def restartInputScope : OraclePredicate RestartInput := fun n O S z => ∃ (m : SamplerModel n O),m.Bounded S ∧ ∃ h : m.Hist,h.length≤S ∧ ∃ k,k≤S ∧ z=m.restartInput h k lemma restartInputScope_width : ∀ n O S z,restartInputScope n O S z → width z≤(sourceWidthPoly 210).eval S := by intro n O S z hz obtain ⟨m,hm,h,hh,k,hk,rfl⟩ := hz exact m.width_restartInput S hm h hh k hk def restartAfterPlainScope : OraclePredicate (.prod RestartInput StateData) := fun n O S z => ∃ (m : SamplerModel n O),m.Bounded S ∧ ∃ h : m.Hist,h.length≤S ∧ ∃ k,k≤S ∧ ∃ x : PlainIndex (pairedSlots n),z=(m.restartInput h k,stateEncode x.val.val) lemma restartAfterPlainScope_width : ∀ n O S z,restartAfterPlainScope n O S z → width z≤(sourceWidthPoly 430).eval S := by intro n O S z hz obtain ⟨m,hm,h,hh,k,hk,x,rfl⟩ := hz have hw := m.width_restartInput S hm h hh k hk rw [width_pair (a:=RestartInput) (b:=StateData),width_stateEncode,eval_sourceWidthPoly] rw [eval_sourceWidthPoly] at hw have hn := hm.1 have hp : S+1≤(S+1)^3 := Nat.le_self_pow (by decide) _ omega lemma safe_restart : OracleSafe restartCode (bankScope restartInputScope) := by unfold restartCode apply oracleSafe_mapControlled _ _ _ _ (by cc) apply oracleSafe_letIn _ _ restartInputScope restartAfterPlainScope · apply oracleSafe_precompose fst plainCode restartInputScope (fun _ _ S x => x≤S) (oracleSafe_controlled _ (by cc) _ _ restartInputScope_width) safe_plain intro n O S z hz y hy obtain ⟨m,hm,h,hh,k,hk,rfl⟩ := hz cases hy exact hm.1 · apply oracleSafe_precompose restartPrep _ restartAfterPlainScope restartRepeatScope (oracleSafe_controlled _ (by unfold restartPrep; cc) _ _ restartAfterPlainScope_width) safe_restartRepeat intro n O S z hz y hy obtain ⟨m,hm,h,hh,k,hk,x,rfl⟩ := hz have he : (k,optionEncode (m.restartValue h 0) (some x))=y := Option.some.inj hy subst y exact ⟨hk,m,hm,h,hh,x,rfl⟩ · intro n O S z bank hz hb y rest hy obtain ⟨m,hm,h,hh,k,hk,rfl⟩ := hz have hl := law_precompose O fst plainCode _ (m.restartInput h k) n _ rfl (plainCode_source O) obtain ⟨x,he,_,hr⟩ := hl.output_some_all (fun _ => True) (DrawTree.all_of_forall _ _ (by intros; trivial)) bank y rest hy exact ⟨⟨m,hm,h,hh,k,hk,x,by rw [he]⟩,hr.trans hb⟩ end Effect namespace SamplerModel noncomputable def phaseState {n : ℕ} {O : IndependenceOracle n} (m : SamplerModel n O) (h : m.Hist) (x : ChainIndex (pairedSlots n)) : Value (.prod PhaseInput StateData) := (m.phaseValue h,stateEncode x.val) lemma width_phaseState {n : ℕ} {O : IndependenceOracle n} (m : SamplerModel n O) (S : ℕ) (hm : m.Bounded S) (h : m.Hist) (hh : h.length≤S) (x : ChainIndex (pairedSlots n)) : width (m.phaseState h x)≤(sourceWidthPoly 210).eval S := by have hw := m.width_phaseValue S hm h hh rw [phaseState,width_pair (a:=PhaseInput) (b:=StateData),width_stateEncode,eval_sourceWidthPoly] have hn := hm.1 have hp : S+1≤(S+1)^3 := Nat.le_self_pow (by decide) _ omega end SamplerModel namespace Effect def phaseScope : OraclePredicate PhaseInput := fun n O S z => ∃ (m : SamplerModel n O),m.Bounded S ∧ ∃ h : m.Hist,h.length≤S ∧ z=m.phaseValue h lemma phaseScope_width : ∀ n O S z,phaseScope n O S z → width z≤(sourceWidthPoly 100).eval S := by intro n O S z hz obtain ⟨m,hm,h,hh,rfl⟩ := hz rw [eval_sourceWidthPoly] exact m.width_phaseValue S hm h hh lemma safe_phaseRestart : OracleSafe phaseRestartCode (bankScope phaseScope) := by unfold phaseRestartCode apply oracleSafe_precompose phaseRestartPrep restartCode phaseScope restartInputScope (oracleSafe_controlled _ (by unfold phaseRestartPrep; cc) _ _ phaseScope_width) safe_restart intro n O S z hz y hy obtain ⟨m,hm,h,hh,rfl⟩ := hz have he : run O phaseRestartPrep (m.phaseValue h)=some (m.restartInput h h.length) := by simp only [phaseRestartPrep,SamplerModel.phaseValue,params,run_both,run_compose,run_fst,run_snd, Option.bind_some,Option.map_some] rw [run_listLength] simp only [SamplerModel.histValue,historyEncode,List.length_map] rfl have hey := Option.some.inj (he.symm.trans hy) subst y exact ⟨m,hm,h,hh,h.length,hh,rfl⟩ lemma safe_start : OracleSafe startCode (bankScope phaseScope) := by unfold startCode exact oracleSafe_mapControlled _ _ _ safe_phaseRestart (by cc) def phaseStateScope : OraclePredicate (.prod PhaseInput StateData) := fun n O S z => ∃ (m : SamplerModel n O),m.Bounded S ∧ ∃ h : m.Hist,h.length≤S ∧ ∃ x : ChainIndex (pairedSlots n),z=m.phaseState h x lemma phaseStateScope_width : ∀ n O S z,phaseStateScope n O S z → width z≤(sourceWidthPoly 210).eval S := by intro n O S z hz obtain ⟨m,hm,h,hh,x,rfl⟩ := hz exact m.width_phaseState S hm h hh x lemma safe_phaseStep : OracleSafe phaseStepCode (bankScope phaseStateScope) := by unfold phaseStepCode apply oracleSafe_precompose phaseStepPrep storedStepCode phaseStateScope weightScope (oracleSafe_controlled _ (by unfold phaseStepPrep; cc) _ _ phaseStateScope_width) safe_storedStep intro n O S z hz y hy obtain ⟨m,hm,h,hh,x,rfl⟩ := hz have he : run O phaseStepPrep (m.phaseState h x)=some (m.weightValue h h.length x) := by simp only [phaseStepPrep,SamplerModel.phaseState,SamplerModel.phaseValue,params,run_both,run_compose,run_fst,run_snd, Option.bind_some,Option.map_some] rw [run_listLength] simp only [SamplerModel.histValue,historyEncode,List.length_map] rfl have hey := Option.some.inj (he.symm.trans hy) subst y exact ⟨m,hm,h,hh,h.length,hh,x,rfl⟩ lemma repeatSample_length {X : Type*} (f : X → DrawTree X) (k : ℕ) (acc : List X) (x : X) : DrawTree.All (fun s => s.1.length=acc.length+k) (treeRepeat (sampleTickTree f) k (acc,x)) := by induction k generalizing acc x with | zero => exact Nat.add_zero _ |>.symm | succ k ih => unfold treeRepeat sampleTickTree rw [DrawTree.map_bind] apply DrawTree.all_bind_of_all (f x) _ (fun _ => True) _ (DrawTree.all_of_forall _ _ (by intros; trivial)) intro y _ exact (ih (x::acc) y).mono (by intro s hs; simpa only [List.length_cons,Nat.add_assoc,Nat.add_comm 1 k] using hs) abbrev SampleNodeData := DataType.prod PhaseInput StateData abbrev SampleAccData := DataType.prod (.list SampleNodeData) SampleNodeData noncomputable def sampleAccValue {n : ℕ} {O : IndependenceOracle n} (m : SamplerModel n O) (h : m.Hist) (s : List (ChainIndex (pairedSlots n)) × ChainIndex (pairedSlots n)) : Value SampleAccData := (s.1.map (m.phaseState h),m.phaseState h s.2) def sampleAccWidth : SizePolynomial := .add (.mul (.constant 2) (.mul .input (.add (.mul (.constant 2) (sourceWidthPoly 210)) (.constant 2)))) (.add (.constant 1) (sourceWidthPoly 210)) lemma sampleAccValue_width {n : ℕ} {O : IndependenceOracle n} (m : SamplerModel n O) (S : ℕ) (hm : m.Bounded S) (h : m.Hist) (hh : h.length≤S) (acc : List (ChainIndex (pairedSlots n))) (ha : acc.length≤S) (x : ChainIndex (pairedSlots n)) : width (sampleAccValue m h (acc,x))≤ sampleAccWidth.eval S := by have hw : ∀ y,width (m.phaseState h y)≤(sourceWidthPoly 210).eval S := m.width_phaseState S hm h hh have hl : width (a:=.list SampleNodeData) (acc.map (m.phaseState h))≤ S*(2*(sourceWidthPoly 210).eval S+2) := by apply (width_list_le _ _ ?_).trans · simp only [List.length_map]; exact Nat.mul_le_mul_right _ ha · intro y hy obtain ⟨z,hz,rfl⟩ := List.mem_map.mp hy exact hw z rw [sampleAccValue,width_pair (a:=.list SampleNodeData) (b:=SampleNodeData)] change 2*width (a:=.list SampleNodeData) (acc.map (m.phaseState h))+1+width (m.phaseState h x) ≤ 2*(S*(2*(sourceWidthPoly 210).eval S+2))+(1+(sourceWidthPoly 210).eval S) have hx := hw x omega def sampleAccScope : OraclePredicate SampleAccData := fun n O S z => ∃ (m : SamplerModel n O),m.Bounded S ∧ ∃ h : m.Hist,h.length≤S ∧ ∃ acc : List (ChainIndex (pairedSlots n)),acc.length≤S ∧ ∃ x : ChainIndex (pairedSlots n),z=sampleAccValue m h (acc,x) lemma sampleAccScope_width : ∀ n O S z,sampleAccScope n O S z → width z≤ sampleAccWidth.eval S := by intro n O S z hz obtain ⟨m,hm,h,hh,acc,ha,x,rfl⟩ := hz exact sampleAccValue_width m S hm h hh acc ha x lemma safe_sampleTick : OracleSafe (sampleTick (withContext phaseStepCode)) (bankScope sampleAccScope) := by unfold sampleTick apply oracleSafe_letControlled _ _ _ _ (by ec) apply oracleSafe_precompose snd _ sampleAccScope phaseStateScope (oracleSafe_controlled _ (by cc) _ _ sampleAccScope_width) (oracleSafe_withContext _ _ safe_phaseStep) intro n O S z hz y hy obtain ⟨m,hm,h,hh,acc,ha,x,rfl⟩ := hz cases hy exact ⟨m,hm,h,hh,x,rfl⟩ def sampleRepeatScope : OraclePredicate (.prod .nat SampleAccData) := fun n O S z => z.1≤S ∧ ∃ (m : SamplerModel n O),m.Bounded S ∧ ∃ h : m.Hist,h.length≤S ∧ ∃ x : ChainIndex (pairedSlots n),z.2=sampleAccValue m h ([],x) lemma safe_sampleRepeat : OracleSafe (repeatCode (sampleTick (withContext phaseStepCode))) (bankScope sampleRepeatScope) := by apply oracleSafe_repeat_law _ sampleRepeatScope sampleAccScope safe_sampleTick (.add .input sampleAccWidth) · intro n O S k z hz obtain ⟨hk,m,hm,h,hh,x,rfl⟩ := hz exact Nat.add_le_add hk (sampleAccValue_width m S hm h hh [] (Nat.zero_le S) x) · intro n O S k z hz j hj obtain ⟨hk,m,hm,h,hh,x,rfl⟩ := hz let f := canonicalStepTree n m.positive m.rank O m.samples h h.length let e := m.phaseState h refine ⟨List (ChainIndex (pairedSlots n)) × ChainIndex (pairedSlots n),sampleAccValue m h, treeRepeat (sampleTickTree f) j ([],x),?_,?_⟩ · apply law_repeat O _ _ _ _ j ([],x) apply law_sampleTick O (withContext phaseStepCode) e f intro y apply law_withContext exact phaseStepCode_source m.M₁ m.M₂ O m.exact m.ground₁ m.ground₂ m.rank m.samples m.phases h m.positive y · apply (repeatSample_length f j [] x).mono intro v hv have hl : v.1.length≤S := by simp only [List.length_nil,Nat.zero_add] at hv exact hv.le.trans (hj.trans hk) exact ⟨(sampleAccValue_width m S hm h hh v.1 hl v.2).trans (Nat.le_add_left _ _), m,hm,h,hh,v.1,hl,v.2,rfl⟩ def sampleInputScope : OraclePredicate (.prod .nat SampleNodeData) := fun n O S z => z.1≤S ∧ phaseStateScope n O S z.2 lemma sampleInputScope_width : ∀ n O S z,sampleInputScope n O S z → width z≤(SizePolynomial.add (.mul (.constant 2) .input) (.add (.constant 1) (sourceWidthPoly 210))).eval S := by intro n O S z hz have hk := (bits_length_le_value z.1).trans hz.1 have hw := phaseStateScope_width n O S z.2 hz.2 rw [width_pair (a:=.nat) (b:=SampleNodeData),width_nat] change _ ≤ 2*S+(1+(sourceWidthPoly 210).eval S) omega lemma safe_sampleCode : OracleSafe (sampleCode (withContext phaseStepCode)) (bankScope sampleInputScope) := by unfold sampleCode apply oracleSafe_precompose _ _ sampleInputScope sampleRepeatScope (oracleSafe_controlled _ (by cc) _ _ sampleInputScope_width) · exact oracleSafe_mapControlled _ _ _ safe_sampleRepeat (by unfold sampleFinish; cc) · intro n O S z hz y hy cases hy obtain ⟨m,hm,h,hh,x,he⟩ := hz.2 exact ⟨hz.1,m,hm,h,hh,x,by rw [he]; rfl⟩ lemma safe_phaseSample : OracleSafe phaseSampleCode (bankScope phaseStateScope) := by unfold phaseSampleCode apply oracleSafe_precompose _ _ phaseStateScope sampleInputScope (oracleSafe_controlled _ (by unfold phaseSamplePrep; cc) _ _ phaseStateScope_width) · exact oracleSafe_mapControlled _ _ _ safe_sampleCode (by unfold mapEach; cc) · intro n O S z hz y hy obtain ⟨m,hm,h,hh,x,rfl⟩ := hz have he : run O phaseSamplePrep (m.phaseState h x)=some (m.samples-1,m.phaseState h x) := by simp only [phaseSamplePrep,SamplerModel.phaseState,SamplerModel.phaseValue,params, run_both,run_compose,run_fst,run_snd,run_ident,run_constant,Option.bind_some,Option.map_some] rw [run_natSub]; rfl have hey := Option.some.inj (he.symm.trans hy) subst y exact ⟨(Nat.sub_le _ _).trans hm.2.2.1,m,hm,h,hh,x,rfl⟩ end Effect open Expression lemma attrSafe_mapStep {a b c : DataType} (p : Expression (.prod a c) b) (A : Attribute (.prod a c)) (hA : A.Mono) (hp : AttrSafe p A) : AttrSafe (mapStep p) (fun S z => A S (z.1,z.2.2)) := by unfold mapStep apply attrSafe_both · apply attrSafe_post _ _ _ _ (by cc) apply attrSafe_both · apply attrSafe_pull _ p _ A (by cc) hp hA intro n O S z hz y hy cases hy; exact hz · exact attrSafe_controlled _ (by cc) _ · exact attrSafe_controlled _ (by cc) _ lemma attrSafe_mapFold {a b c : DataType} (p : Expression (.prod a c) b) (A : Attribute (.prod a c)) (hA : A.Mono) (hp : AttrSafe p A) : AttrSafe (.fold (mapStep p)) (fun S z => ∀ x∈z.1,A S (x,z.2.2)) := by obtain ⟨f,hf⟩ := hp let s : SizePolynomial := .add (.mul (.constant 3) .input) (.constant 1) let g : SizePolynomial := .mul (.add (.mul (.constant 4) .input) (.constant 3)) (.add (.mul (.constant 2) (f.subst s)) (.constant 3)) have hacc : ∀ {n : ℕ} (O : IndependenceOracle n) S xs zs ctx, width (a:=.prod (.list a) (.prod (.list b) c)) (xs,(zs,ctx))≤S → (∀ x∈xs,A S (x,ctx)) → ∀ pre post,xs=pre++post → ∀ y, foldValue (run O (mapStep p)) pre (zs,ctx)=some y → width y≤g.eval S ∧ y.2=ctx := by intro n O S xs zs ctx hw ha pre post he y hy have hx : width (a:=.list a) xs≤S := (width_fst _).trans hw have hzs : width (a:=.list b) zs≤S := (width_fst (a:=.list b) (b:=c) (zs,ctx)).trans ((width_snd _).trans hw) have hc : width ctx≤S := (width_snd (a:=.list b) (b:=c) (zs,ctx)).trans ((width_snd _).trans hw) have hl : pre.length≤S := by have hh := (list_length_le_width xs).trans hx rw [he,List.length_append] at hh omega let U := f.eval (s.eval S) have hh := fold_mapStep_bound O p pre zs ctx U (by intro x hxp v hv have hxx : x∈xs := by rw [he]; exact List.mem_append_left post hxp have hxb := (width_list_member x xs hxx).trans hx apply safe_output (hf O (s.eval S) (x,ctx) ⟨?_,?_⟩) hv · rw [width_pair (a:=a) (b:=c)] change _≤3*S+1 omega · exact hA S _ (by change S≤3*S+1; omega) (x,ctx) (ha x hxx)) y hy have hm := Nat.mul_le_mul_right (2*U+2) hl have hy' : width (a:=.list b) y.1≤S+S*(2*U+2) := by omega refine ⟨?_,hh.2⟩ have hw' : width y=2*width (a:=.list b) y.1+1+width ctx := by rw [width_pair (a:=.list b) (b:=c),hh.2] rw [hw'] simp only [g,SizePolynomial.eval,SizePolynomial.eval_subst] change _≤(4*S+3)*(2*U+3) nlinarith let W : SizePolynomial := .add (.mul (.constant 3) .input) (.add g (.constant 1)) apply polySafe_fold (mapStep p) _ (fun S (z : Value (.prod a (.prod (.list b) c))) => width z≤W.eval S ∧ A (W.eval S) (z.1,z.2.2)) (polySafe_reparam _ _ (attrSafe_mapStep p A hA ⟨f,hf⟩) W) (.add .input g) · intro S z hz; exact hz.1.trans (Nat.le_add_right _ _) · intro n O S xs z hz pre post he y hy exact (hacc O S xs z.1 z.2 hz.1 hz.2 pre post he y hy).1.trans (Nat.le_add_left _ _) · intro n O S xs z hz pre x post he y hy have hh := hacc O S xs z.1 z.2 hz.1 hz.2 pre (x::post) he y hy have hm : x∈xs := by rw [he]; simp have hwx := (width_list_member x xs hm).trans ((width_fst _).trans hz.1) refine ⟨?_,?_⟩ · rw [width_pair (a:=a) (b:=.prod (.list b) c)] change _≤3*S+(g.eval S+1) omega · rw [hh.2] exact hA S _ (by change S≤3*S+(g.eval S+1); omega) (x,z.2) (hz.2 x hm) lemma attrSafe_mapWith {a b c : DataType} (p : Expression (.prod a c) b) (A : Attribute (.prod a c)) (hA : A.Mono) (hp : AttrSafe p A) : AttrSafe (mapWith p) (fun S z => ∀ x∈z.1,A S (x,z.2)) := by unfold mapWith apply attrSafe_pull _ _ _ (fun S (z : Value (.prod (.list a) (.prod (.list b) c))) => ∀ x∈z.1,A S (x,z.2.2)) (by cc) · exact attrSafe_post _ _ _ (attrSafe_mapFold p A hA hp) (by cc) · intro S T h z hz x hx; exact hA S T h (x,z.2.2) (hz x hx) · intro n O S z hz y hy cases hy; exact hz lemma attrSafe_allRange {a : DataType} (p : Expression (.prod .nat a) .bool) (A : Attribute (.prod .nat a)) (hA : A.Mono) (hp : AttrSafe p A) : AttrSafe (allRange p) (fun S z => z.1≤S ∧ ∀ i ∀ i∈z.1,A S (i,z.2)) · apply attrSafe_both · apply attrSafe_pull fst rangeCode _ _ (by cc) attr_rangeCode · intro S T h x hx; exact hx.trans h · intro n O S z hz y hy; cases hy; exact hz.1 · exact attrSafe_controlled _ (by cc) _ · exact attrSafe_post _ _ _ (attrSafe_mapWith p A hA hp) (by cc) · intro S T h z hz i hi; exact hA S T h (i,z.2) (hz i hi) · intro n O S z hz y hy have he : run O (both (fst >>> rangeCode) snd) z=some (List.range z.1,z.2) := by simp only [run_both,run_compose,run_fst,run_snd,Option.bind_some,run_rangeCode,Option.map_some] have hey := Option.some.inj (he.symm.trans hy) subst y intro i hi exact hz.2 i (List.mem_range.mp hi) lemma controlled_pairPositive : Controlled pairPositiveCode := by have h := controlled_historyWeight unfold pairPositiveCode cc lemma attr_slotRow : AttrSafe slotRowCode (fun S z => z.2.1≤S) := by unfold slotRowCode apply attrSafe_pull _ _ _ (fun S (z : Value (.prod .nat (.prod .nat HistoryData))) => z.1≤S ∧ ∀ i True) (by intro S T h z hz; exact True.intro) (attrSafe_controlled _ (by have h := controlled_pairPositive; cc) _) · intro S T h z hz; exact ⟨hz.1.trans h,by intros; trivial⟩ · intro n O S z hz y hy; cases hy; exact ⟨hz,by intros; trivial⟩ lemma attr_slotsPositive : AttrSafe slotsPositiveCode (fun S z => z.1≤S) := by unfold slotsPositiveCode apply attrSafe_pull _ _ _ (fun S (z : Value (.prod .nat (.prod .nat HistoryData))) => z.1≤S ∧ ∀ i z.2.1≤S) (by intro S T h z hz; exact hz.trans h) attr_slotRow · intro S T h z hz; exact ⟨hz.1.trans h,fun i hi => (hz.2 i hi).trans h⟩ · intro n O S z hz y hy; cases hy; exact ⟨hz,fun _ _ => hz⟩ lemma attr_prefixPositive : AttrSafe prefixPositiveCode (fun S z => z.2.1≤S) := by unfold prefixPositiveCode apply attrSafe_pull _ _ _ (fun S (z : Value (.prod .nat HistoryData)) => z.1≤S) (by cc) attr_slotsPositive · intro S T h z hz; exact hz.trans h · intro n O S z hz y hy have he : z.2.1=y.1 := Option.some.inj (run_both_parts O _ _ z y hy).1 exact he ▸ hz lemma attr_historyPositive : AttrSafe historyPositiveCode (fun S z => z.1≤S) := by let prep : Expression (.prod .nat HistoryData) (.prod .nat (.prod .nat HistoryData)) := both (snd >>> listLength >>> (both ident (constant 1) >>> add)) ident have hc : Controlled prep := by dsimp [prep]; cc obtain ⟨f,hf⟩ := hc let g : SizePolynomial := .add f (.add .input (.constant 1)) change PolySafe (prep >>> allRange prefixPositiveCode) (fun S z => width z≤S ∧ z.1≤S) apply polySafe_compose prep _ _ (fun S z => width z≤g.eval S ∧ (z.1≤g.eval S ∧ ∀ i z.2.1≤S) (by intro S T h z hz; exact hz.trans h) attr_prefixPositive) g) intro n O S z hz y hy have hd : y=(z.2.length+1,z) := by have he : run O prep z=some (z.2.length+1,z) := by simp only [prep,run_both,run_compose,run_snd,run_ident,run_constant, Option.bind_some,Option.map_some,run_listLength] rfl exact Option.some.inj (hy.symm.trans he) have hw : width y≤f.eval S := (safe_output (hf O z) hy).trans (f.monotone hz.1) have hl := (list_length_le_width z.2).trans ((width_snd (a:=.nat) (b:=HistoryData) z).trans hz.1) refine ⟨hw.trans (Nat.le_add_right _ _),?_,?_⟩ · rw [hd] change z.2.length+1≤f.eval S+(S+1) omega · intro i hi rw [hd] exact hz.2.trans (by change S≤f.eval S+(S+1); omega) open Expression open scoped Classical namespace Effect lemma oracleSafe_chooseScoped {a b : DataType} (t : Expression a .bool) (p q : Effect a b) (R : OraclePredicate a) (ht : OracleSafe t R) (hp : OracleSafe p (bankScope R)) (hq : OracleSafe q (bankScope R)) : OracleSafe (choose t p q) (bankScope R) := by apply oracleSafe_applyIf _ _ _ (bankScope R) · exact safe_scope_fst t R ht · exact oracleSafe_mono p hp (by intro n O S x hx; exact hx.1) · exact oracleSafe_mono q hq (by intro n O S x hx; exact hx.1) lemma oracleSafe_some {a b : DataType} (p : Effect a b) (R : OraclePredicate (.prod a BankData)) (hp : OracleSafe p R) : OracleSafe (someCode p) R := by unfold someCode exact oracleSafe_mapControlled _ _ R hp (by cc) lemma attr_positiveTest : AttrSafe positiveTest (fun S z => z.1.1.1≤S) := by unfold positiveTest apply attrSafe_pull _ _ _ (fun S (z : Value (.prod .nat HistoryData)) => z.1≤S) (by cc) attr_historyPositive · intro S T h z hz; exact hz.trans h · intro n O S z hz y hy; cases hy; exact hz lemma safe_positiveTest : OracleSafe positiveTest phaseScope := by apply oracleSafe_attr _ _ (by intro S T h z hz; exact hz.trans h) attr_positiveTest phaseScope _ phaseScope_width intro n O S z hz obtain ⟨m,hm,h,hh,rfl⟩ := hz exact hm.1 lemma safe_phaseNone : OracleSafe (noneCode (a:=PhaseInput) (b:=SampleData)) (bankScope phaseScope) := by exact oracleSafe_pure _ phaseScope (oracleSafe_controlled _ (by cc) _ _ phaseScope_width) lemma safe_phase : OracleSafe phaseCode (bankScope phaseScope) := by unfold phaseCode apply oracleSafe_chooseScoped _ _ _ phaseScope safe_positiveTest safe_phaseNone apply oracleSafe_optionBind _ _ phaseScope phaseStateScope (oracleSafe_retainOption _ _ safe_start) (oracleSafe_some _ _ safe_phaseSample) intro n O S z bank hz hb y rest hy obtain ⟨m,hm,h,hh,rfl⟩ := hz have hl := law_retainOption O startCode (fun x : ChainIndex (pairedSlots n) => stateEncode x.val) (m.phaseValue h) _ (startCode_source m.M₁ m.M₂ O m.exact m.ground₁ m.ground₂ m.rank m.samples m.phases h m.positive) obtain ⟨v,he,hr⟩ := hl.output_some bank y rest hy refine ⟨?_,hr.trans hb⟩ rw [he] apply optionScope_encode intro x exact ⟨m,hm,h,hh,x,rfl⟩ lemma safe_witness : OracleSafe witnessCode (bankScope phaseScope) := by unfold witnessCode apply oracleSafe_chooseScoped _ _ _ phaseScope safe_positiveTest _ safe_phaseRestart exact oracleSafe_pure _ phaseScope (oracleSafe_controlled _ (by cc) _ _ phaseScope_width) end Effect section open Expression open scoped Classical namespace Expression def weightedPlainCode : Expression (.prod .nat StateData) NN := applyIf (snd >>> plainCode) (constant (0,1)) (both (both (both fst (constant 1)) (constant [])) snd >>> annealCode) def weightedListCode : Expression (.prod .nat SampleData) (.list NN) := both snd fst >>> mapWith (Expression.swap >>> weightedPlainCode) def weightedMeanCode : Expression (.prod .nat SampleData) NN := letIn weightedListCode (both (snd >>> ratSumCode) (fst >>> snd >>> listLength >>> natRatCode) >>> ratDiv) def plainMeanCode : Expression (.prod .nat SampleData) NN := both (snd >>> countPlainCode) (snd >>> listLength) >>> normalizeRat def ratioCode : Expression (.prod .nat SampleData) NN := both weightedMeanCode plainMeanCode >>> ratDiv end Expression variable {n : ℕ} (M₁ M₂ : Matroid (Fin n)) (O : IndependenceOracle n) (hO : ExactOracles M₁ M₂ O) (hE₁ : M₁.E=Set.univ) (hE₂ : M₂.E=Set.univ) (r : ℕ) local notation "GS" => pairedSlots n local notation "f" => (fun S => rationalPlain GS (fun S => rationalRho n^oracleDeficiency n r O S) S) lemma weightedPlain_nonneg (S : Set (Fin n⊕Fin n)) : 0≤f S := by change 0 ≤ if PlainState GS S then rationalRho n ^ oracleDeficiency n r O S else 0 split_ifs · exact pow_nonneg (Expression.rationalRho_nonneg n) _ · rfl include M₁ M₂ hO hE₁ hE₂ lemma weightedPlainCode_source (S : Set (Fin n⊕Fin n)) : run O weightedPlainCode (r,stateEncode S)=some (rationalPair (f S)) := by rw [weightedPlainCode,run_applyIf] change ((run O Expression.plainCode (stateEncode S)).bind fun b => _)=_ rw [plainCode_source] by_cases hs : PlainState GS S · simp only [hs,decide_true,Option.bind_some,ite_true] change run O annealCode (((r,1),historyEncode ([] : List (List (Set (Fin n⊕Fin n))))),stateEncode S)=_ rw [annealCode_source M₁ M₂ O hO hE₁ hE₂] simp only [rationalPlain,hs,ite_true,pow_one] · simp only [hs,decide_false,Option.bind_some,Bool.false_eq_true,ite_false,run_constant,rationalPlain] rfl lemma weightedListCode_source (xs : List (Set (Fin n⊕Fin n))) : run O weightedListCode (r,sampleEncode xs)=some ((xs.map f).map rationalPair) := by change run O (mapWith (Expression.swap >>> weightedPlainCode)) (xs.map stateEncode,r)=_ rw [run_mapWith_source O (Expression.swap >>> weightedPlainCode) stateEncode (fun S => rationalPair (f S)) r (weightedPlainCode_source M₁ M₂ O hO hE₁ hE₂ r) xs] simp only [List.map_map,Function.comp_def] lemma weightedMeanCode_source (xs : List (Set (Fin n⊕Fin n))) : run O weightedMeanCode (r,sampleEncode xs)=some (rationalPair (rationalEmpirical f xs)) := by rw [weightedMeanCode,run_letIn,weightedListCode_source M₁ M₂ O hO hE₁ hE₂ r xs,Option.bind_some] simp only [run_compose,run_both,run_fst,run_snd,Option.bind_some] rw [run_ratSumCode O (xs.map f) (by intro q hq; obtain ⟨S,hS,rfl⟩ := List.mem_map.mp hq; exact weightedPlain_nonneg O r S)] simp only [Option.bind_some] rw [run_listLength] simp only [sampleEncode,List.length_map,Option.bind_some] rw [run_natRatCode] simp only [Option.bind_some,Option.map_some] apply run_ratDiv · exact List.sum_nonneg (by intro q hq; obtain ⟨S,hS,rfl⟩ := List.mem_map.mp hq; exact weightedPlain_nonneg O r S) · positivity omit M₁ M₂ hO hE₁ hE₂ in lemma plainMeanCode_source (xs : List (Set (Fin n⊕Fin n))) : run O plainMeanCode (r,sampleEncode xs)=some (rationalPair (rationalEmpirical (rationalPlain GS (fun _ => 1)) xs)) := by simp only [plainMeanCode,run_compose,run_both,run_snd,Option.bind_some] rw [run_countPlainCode,run_listLength] simp only [Option.bind_some,Option.map_some] rw [run_normalizeRat_pair,countPlainValue_source] unfold rationalEmpirical rationalPlain dsimp only rw [indicator_list_sum] simp only [sampleEncode,List.length_map] lemma ratioCode_source (xs : List (Set (Fin n⊕Fin n))) : run O ratioCode (r,sampleEncode xs)=some (rationalPair (rationalRatio GS (fun S => rationalRho n^oracleDeficiency n r O S) xs)) := by simp only [ratioCode,run_compose,run_both] rw [weightedMeanCode_source M₁ M₂ O hO hE₁ hE₂ r xs,plainMeanCode_source O r xs] simp only [Option.bind_some,Option.map_some] apply run_ratDiv · unfold rationalEmpirical apply div_nonneg · apply List.sum_nonneg intro q hq obtain ⟨S,hS,rfl⟩ := List.mem_map.mp hq exact weightedPlain_nonneg O r S · positivity · unfold rationalEmpirical rationalPlain rw [indicator_list_sum] positivity end section open Expression namespace Effect def historyTickCode {a c} (p : Effect (.prod c (.list a)) (Optional a)) : Effect (.prod c (.list a)) (Optional (.prod c (.list a))) := map (retainOption p) (optionMapCode (both (fst >>> fst) (both (fst >>> snd) (both snd (constant []) >>> cons) >>> listAppend))) def historyTickTree {X : Type*} (K : List X → DrawTree (Option X)) (h : List X) : DrawTree (Option (List X)) := (K h).map (Option.map (fun x => h++[x])) lemma optionRepeat_none {X : Type*} (f : X → DrawTree (Option X)) (k : ℕ) : treeRepeat (fun x => match x with | none => .leaf none | some y => f y) k none=.leaf none := by induction k with | zero => rfl | succ k ih => exact ih lemma iterate_history {X : Type*} (K : List X → DrawTree (Option X)) (k : ℕ) (h : List X) : DrawTree.iterate (historyTickTree K) k h=DrawTree.history K k h := by rw [←treeRepeat_option] induction k generalizing h with | zero => rfl | succ k ih => simp only [treeRepeat,historyTickTree,DrawTree.map_bind,DrawTree.history,DrawTree.optionBind] congr 1 funext u cases u with | none => exact optionRepeat_none _ k | some x => exact ih (h++[x]) lemma law_historyTickCode {n : ℕ} (O : IndependenceOracle n) {X : Type*} {a c} (p : Effect (.prod c (.list a)) (Optional a)) (e : X → Value a) (ctx : Value c) (K : List X → DrawTree (Option X)) (h : List X) (hp : RealizesLaw O p (optionEncode e) (ctx,h.map e) (K h)) : RealizesLaw O (historyTickCode p) (optionEncode (fun h => (ctx,h.map e))) (ctx,h.map e) (historyTickTree K h) := by apply law_optionMap O (retainOption p) _ (fun y => ((ctx,h.map e),e y)) _ _ _ (fun x => h++[x]) · exact law_retainOption O p e (ctx,h.map e) (K h) hp · intro x simp only [run_both,run_compose,run_fst,run_snd,run_constant,Option.bind_some,Option.map_some] change ((run O listAppend (h.map e,[e x])).map fun l => (ctx,l))=_ rw [run_listAppend] simp def historyCode {a c} (p : Effect (.prod c (.list a)) (Optional a)) : Effect (.prod .nat (.prod c (.list a))) (Optional (.prod c (.list a))) := iterateCode (historyTickCode p) lemma law_historyCode {n : ℕ} (O : IndependenceOracle n) {X : Type*} {a c} (p : Effect (.prod c (.list a)) (Optional a)) (e : X → Value a) (ctx : Value c) (K : List X → DrawTree (Option X)) (hp : ∀ h,RealizesLaw O p (optionEncode e) (ctx,h.map e) (K h)) (k : ℕ) (h : List X) : RealizesLaw O (historyCode p) (optionEncode (fun h => (ctx,h.map e))) (k,(ctx,h.map e)) (DrawTree.history K k h) := by rw [←iterate_history] exact law_iterate O (historyTickCode p) _ _ (fun h => law_historyTickCode O p e ctx K h (hp h)) k h end Effect open Expression open scoped BigOperators Classical namespace Expression def historyAtCode : Expression (.prod HistoryData .nat) SampleData := both ident (constant []) >>> getDCode def ratioAtCode : Expression (.prod .nat PhaseInput) NN := both (snd >>> fst >>> fst >>> snd) (both (snd >>> snd) fst >>> historyAtCode) >>> ratioCode def estimateCode : Expression PhaseInput NN := both (both (constant (b:=.nat) 2) (fst >>> fst >>> fst : Expression PhaseInput .nat) >>> Expression.powCode >>> natRatCode) (both (fst >>> snd >>> fst >>> snd >>> rangeCode) ident >>> mapWith ratioAtCode >>> ratProductCode) >>> ratMul def guardCode : Expression (.prod PhaseInput StateData) NN := applyIf (both (fst >>> fst >>> fst >>> snd) snd >>> deficiencyCode >>> natEqZero) (constant (0,1)) (fst >>> estimateCode) end Expression lemma historyAtCode_source {n N : ℕ} (O : IndependenceOracle n) (h : List (PhaseSample n N)) (j : ℕ) : run O historyAtCode (historyEncode (h.map (observedSets n N)),j)= some (sampleEncode (historySample (observedSets n N) h j)) := by change run O getDCode ((historyEncode (h.map (observedSets n N)),j),[])=_ rw [run_getDCode] unfold historyEncode historySample simp only [List.getD_eq_getElem?_getD,List.getElem?_map] cases h[j]? <;> rfl lemma ratio_nonnegative {n : ℕ} (O : IndependenceOracle n) (r : ℕ) (xs : List (Set (Fin n⊕Fin n))) : 0≤rationalRatio (pairedSlots n) (fun S => rationalRho n^oracleDeficiency n r O S) xs := by unfold rationalRatio rationalEmpirical apply div_nonneg · apply div_nonneg · apply List.sum_nonneg intro q hq obtain ⟨S,hS,rfl⟩ := List.mem_map.mp hq exact weightedPlain_nonneg O r S · positivity · apply div_nonneg · unfold rationalPlain rw [indicator_list_sum] positivity · positivity variable {n : ℕ} (M₁ M₂ : Matroid (Fin n)) (O : IndependenceOracle n) (hO : ExactOracles M₁ M₂ O) (hE₁ : M₁.E=Set.univ) (hE₂ : M₂.E=Set.univ) (r N L : ℕ) local notation "GS" => pairedSlots n include M₁ M₂ hO hE₁ hE₂ lemma ratioAtCode_source (h : List (PhaseSample n N)) (j : ℕ) : run O ratioAtCode (j,(params n r N L,historyEncode (h.map (observedSets n N))))= some (rationalPair (rationalRatio GS (fun S => rationalRho n^oracleDeficiency n r O S) (historySample (observedSets n N) h j))) := by simp only [ratioAtCode,run_compose,run_both,run_fst,run_snd,params,Option.bind_some,Option.map_some] rw [historyAtCode_source] simp only [Option.bind_some,Option.map_some] exact ratioCode_source M₁ M₂ O hO hE₁ hE₂ r _ lemma estimateCode_source (h : List (PhaseSample n N)) : run O estimateCode (params n r N L,historyEncode (h.map (observedSets n N)))= some (rationalPair (oracleEstimate n r O N L h)) := by simp only [estimateCode,run_compose,run_both,run_fst,run_snd,run_ident,run_constant,params,Option.bind_some,Option.map_some] rw [run_powCode,Option.bind_some,run_natRatCode,Option.bind_some,run_rangeCode] simp only [Option.bind_some] let f : ℕ → ℚ := fun j => rationalRatio GS (fun S => rationalRho n^oracleDeficiency n r O S) (historySample (observedSets n N) h j) have hm := run_mapWith_source O ratioAtCode id (fun j => rationalPair (f j)) (params n r N L,historyEncode (h.map (observedSets n N))) (ratioAtCode_source M₁ M₂ O hO hE₁ hE₂ r N L h) (List.range L) simp only [List.map_id,params] at hm rw [run_compose,hm] simp only [Option.bind_some] have he : (List.range L).map (fun j => rationalPair (f j))=((List.range L).map f).map rationalPair := by simp only [List.map_map,Function.comp_def] rw [he,run_ratProductCode O _ (by intro q hq obtain ⟨j,hj,rfl⟩ := List.mem_map.mp hq exact ratio_nonnegative O r _)] simp only [Option.bind_some,Option.map_some] rw [run_ratMul O _ _ (by positivity) (by apply List.prod_nonneg intro q hq obtain ⟨j,hj,rfl⟩ := List.mem_map.mp hq exact ratio_nonnegative O r _)] congr 2 unfold oracleEstimate rw [Nat.cast_pow,Nat.cast_ofNat] congr 1 lemma guardCode_source (h : List (PhaseSample n N)) (x : PlainIndex GS) : run O guardCode ((params n r N L,historyEncode (h.map (observedSets n N))),stateEncode x.val.val)= some (rationalPair (oracleGuard n r O N L h x)) := by rw [guardCode,run_applyIf] simp only [run_compose,run_both,run_fst,run_snd,params,Option.bind_some,Option.map_some] rw [deficiencyCode_source M₁ M₂ O hO hE₁ hE₂ r _ _ (stateEncode_left_length _) (stateEncode_right_length _), stateEncode_repr,Option.bind_some,run_natEqZero] by_cases hz : oracleDeficiency n r O x.val.val=0 · simp only [hz,decide_true,Option.bind_some,ite_true] simpa only [params,oracleGuard,hz,ite_true] using estimateCode_source M₁ M₂ O hO hE₁ hE₂ r N L h · simp only [hz,decide_false,Option.bind_some,Bool.false_eq_true,ite_false,run_constant,oracleGuard] rfl end section open Expression open Effect open scoped Classical namespace Effect def finalGuardCode : Effect PhaseInput (Optional NN) := map (retainOption witnessCode) (optionMapCode guardCode) def algorithmHistoryCode : Effect AlgorithmParams (Optional PhaseInput) := precompose (both (snd >>> fst >>> snd) (both ident (constant []))) (historyCode phaseCode) def algorithmCode : Effect AlgorithmParams (Optional NN) := optionBind algorithmHistoryCode finalGuardCode end Effect variable {n : ℕ} (M₁ M₂ : Matroid (Fin n)) (O : IndependenceOracle n) (hO : ExactOracles M₁ M₂ O) (hE₁ : M₁.E=Set.univ) (hE₂ : M₂.E=Set.univ) (r N L : ℕ) (hn : 0 pairedSlots n include M₁ M₂ hO hE₁ hE₂ lemma algorithmHistoryCode_source : RealizesLaw O algorithmHistoryCode (optionEncode (fun h : List (PhaseSample n N) => (params n r N L,historyEncode (h.map (observedSets n N))))) (params n r N L) (DrawTree.history (canonicalPhaseTree n hn r O N L) L []) := by apply law_precompose O _ _ _ _ _ _ rfl have hh := law_historyCode O phaseCode (fun v : PhaseSample n N => sampleEncode (observedSets n N v)) (params n r N L) (canonicalPhaseTree n hn r O N L) (fun h => by simpa only [historyEncode,List.map_map,Function.comp_def] using phaseCode_source M₁ M₂ O hO hE₁ hE₂ r N L h hn) L [] simpa only [historyEncode,List.map_map,Function.comp_def,List.map_nil] using hh lemma finalGuardCode_source (h : List (PhaseSample n N)) : RealizesLaw O finalGuardCode (optionEncode rationalPair) (params n r N L,historyEncode (h.map (observedSets n N))) ((canonicalWitnessTree n hn r O N L h).map (Option.map (oracleGuard n r O N L h))) := by apply law_optionMap O (retainOption witnessCode) guardCode (fun x : PlainIndex GS => ((params n r N L,historyEncode (h.map (observedSets n N))),stateEncode x.val.val)) rationalPair _ _ (oracleGuard n r O N L h) · exact law_retainOption O witnessCode _ _ _ (witnessCode_source M₁ M₂ O hO hE₁ hE₂ r N L h hn) · exact guardCode_source M₁ M₂ O hO hE₁ hE₂ r N L h lemma algorithmCode_source : RealizesLaw O algorithmCode (optionEncode rationalPair) (params n r N L) (canonicalAlgorithmTree n hn r O N L) := by exact law_optionBind O algorithmHistoryCode finalGuardCode (fun h : List (PhaseSample n N) => (params n r N L,historyEncode (h.map (observedSets n N)))) rationalPair (params n r N L) _ _ (algorithmHistoryCode_source M₁ M₂ O hO hE₁ hE₂ r N L hn) (fun h => finalGuardCode_source M₁ M₂ O hO hE₁ hE₂ r N L hn h) end open Expression open scoped Classical namespace Effect lemma history_length {X : Type*} (K : List X → DrawTree (Option X)) (k : ℕ) (h : List X) : DrawTree.All (fun v => ∀ h',v=some h' → h'.length=h.length+k) (DrawTree.history K k h) := by induction k generalizing h with | zero => intro h' he; cases he; simp | succ k ih => unfold DrawTree.history DrawTree.optionBind apply DrawTree.all_bind_of_all (K h) _ (fun _ => True) _ (DrawTree.all_of_forall _ _ (by intros; trivial)) intro u _ cases u with | none => intro h' he; cases he | some x => apply (ih (h++[x])).mono intro v hv h' he have hh := hv h' he simpa only [List.length_append,List.length_singleton,Nat.add_assoc,Nat.add_comm 1 k] using hh lemma safe_historyTick : OracleSafe (historyTickCode phaseCode) (bankScope phaseScope) := by unfold historyTickCode exact oracleSafe_mapControlled _ _ _ (oracleSafe_retainOption _ _ safe_phase) (by cc) noncomputable def phaseOptWidth : SizePolynomial := .add (sourceWidthPoly 100) (.constant (width (zeroValue PhaseInput)+3)) lemma phaseOptWidth_bound {n : ℕ} {O : IndependenceOracle n} (m : SamplerModel n O) (S : ℕ) (hm : m.Bounded S) (v : Option m.Hist) (hv : ∀ h,v=some h → h.length≤S) : width (optionEncode m.phaseValue v)≤phaseOptWidth.eval S := by cases v with | none => rw [optionEncode,optionalValue,width_pair (a:=.bool) (b:=PhaseInput),width_bool] change 2*1+1+width (zeroValue PhaseInput)≤(sourceWidthPoly 100).eval S+(width (zeroValue PhaseInput)+3) omega | some h => have hw := m.width_phaseValue S hm h (hv h rfl) rw [optionEncode,optionalValue,width_pair (a:=.bool) (b:=PhaseInput),width_bool] change 2*1+1+width (m.phaseValue h)≤(sourceWidthPoly 100).eval S+(width (zeroValue PhaseInput)+3) rw [eval_sourceWidthPoly] omega lemma historyTick_source {n : ℕ} {O : IndependenceOracle n} (m : SamplerModel n O) (h : m.Hist) : RealizesLaw O (historyTickCode phaseCode) (optionEncode m.phaseValue) (m.phaseValue h) (historyTickTree (canonicalPhaseTree n m.positive m.rank O m.samples m.phases) h) := by have hl := law_historyTickCode O phaseCode (fun v : PhaseSample n m.samples => sampleEncode (observedSets n m.samples v)) (params n m.rank m.samples m.phases) (canonicalPhaseTree n m.positive m.rank O m.samples m.phases) h (by simpa only [SamplerModel.phaseValue,SamplerModel.histValue,historyEncode,List.map_map,Function.comp_def] using phaseCode_source m.M₁ m.M₂ O m.exact m.ground₁ m.ground₂ m.rank m.samples m.phases h m.positive) change RealizesLaw O _ (optionEncode (fun h => m.phaseValue h)) _ _ simpa only [SamplerModel.phaseValue,SamplerModel.histValue,historyEncode,List.map_map,Function.comp_def] using hl def historyRepeatScope : OraclePredicate (.prod .nat (Optional PhaseInput)) := fun n O S z => z.1≤S ∧ ∃ (m : SamplerModel n O),m.Bounded S ∧ z.2=optionEncode m.phaseValue (some []) lemma safe_historyRepeat : OracleSafe (repeatCode (optionContinue (historyTickCode phaseCode))) (bankScope historyRepeatScope) := by apply oracleSafe_repeat_law _ historyRepeatScope (optionScope phaseScope) (oracleSafe_optionContinue _ _ safe_historyTick) (.add .input phaseOptWidth) · intro n O S k z hz obtain ⟨hk,m,hm,rfl⟩ := hz exact Nat.add_le_add hk (phaseOptWidth_bound m S hm (some []) (by intro h he; cases he; exact Nat.zero_le S)) · intro n O S k z hz j hj obtain ⟨hk,m,hm,rfl⟩ := hz let K := canonicalPhaseTree n m.positive m.rank O m.samples m.phases let f := historyTickTree K let F : Option m.Hist → DrawTree (Option m.Hist) := fun u => match u with | none => .leaf none | some h => f h refine ⟨Option m.Hist,optionEncode m.phaseValue,treeRepeat F j (some []),?_,?_⟩ · apply law_repeat O _ _ F _ j (some []) intro u change RealizesLaw O (optionContinue (historyTickCode phaseCode)) (optionEncode m.phaseValue) (optionEncode m.phaseValue u) (match u with | none => .leaf none | some h => f h) cases u <;> exact law_optionContinue O (historyTickCode phaseCode) m.phaseValue m.phaseValue f _ (fun h => historyTick_source m h) · have he : treeRepeat F j (some [])=DrawTree.iterate f j [] := by convert treeRepeat_option f j ([] : m.Hist) using 2 funext u; cases u <;> rfl rw [he] change DrawTree.All _ (DrawTree.iterate (historyTickTree K) j []) rw [iterate_history] apply (history_length K j []).mono intro v hv have hb : ∀ h,v=some h → h.length≤S := by intro h he have hh := hv h he simp only [List.length_nil,Nat.zero_add] at hh exact hh.le.trans (hj.trans hk) refine ⟨(phaseOptWidth_bound m S hm v hb).trans (Nat.le_add_left _ _),?_⟩ cases v with | none => exact Or.inl rfl | some h => exact Or.inr ⟨rfl,m,hm,h,hb h rfl,rfl⟩ def historyInputScope : OraclePredicate (.prod .nat PhaseInput) := fun n O S z => z.1≤S ∧ ∃ (m : SamplerModel n O),m.Bounded S ∧ z.2=m.phaseValue [] lemma historyInputScope_width : ∀ n O S z,historyInputScope n O S z → width z≤(SizePolynomial.add (.mul (.constant 2) .input) (.add (.constant 1) (sourceWidthPoly 100))).eval S := by intro n O S z hz obtain ⟨hk,m,hm,he⟩ := hz have hb := (bits_length_le_value z.1).trans hk have hw := m.width_phaseValue S hm [] (Nat.zero_le S) rw [width_pair (a:=.nat) (b:=PhaseInput),width_nat,he] change _≤2*S+(1+(sourceWidthPoly 100).eval S) rw [eval_sourceWidthPoly] omega lemma safe_historyCode : OracleSafe (historyCode phaseCode) (bankScope historyInputScope) := by unfold historyCode iterateCode apply oracleSafe_precompose _ _ historyInputScope historyRepeatScope (oracleSafe_controlled _ (by cc) _ _ historyInputScope_width) safe_historyRepeat intro n O S z hz y hy cases hy obtain ⟨hk,m,hm,he⟩ := hz exact ⟨hk,m,hm,by rw [he]; rfl⟩ def algorithmScope : OraclePredicate AlgorithmParams := fun n O S z => ∃ (m : SamplerModel n O),m.Bounded S ∧ z=params n m.rank m.samples m.phases lemma algorithmScope_width : ∀ n O S z,algorithmScope n O S z → width z≤(sourceWidthPoly 100).eval S := by intro n O S z hz obtain ⟨m,hm,rfl⟩ := hz rw [eval_sourceWidthPoly] exact (width_fst (a:=AlgorithmParams) (b:=HistoryData) (m.phaseValue [])).trans (m.width_phaseValue S hm [] (Nat.zero_le S)) lemma safe_algorithmHistory : OracleSafe algorithmHistoryCode (bankScope algorithmScope) := by unfold algorithmHistoryCode apply oracleSafe_precompose _ _ algorithmScope historyInputScope (oracleSafe_controlled _ (by cc) _ _ algorithmScope_width) safe_historyCode intro n O S z hz y hy obtain ⟨m,hm,rfl⟩ := hz cases hy exact ⟨hm.2.2.2.1,m,hm,rfl⟩ end Effect open Expression lemma attrSafe_fst {a b c : DataType} (p : Expression a c) (A : Attribute a) (hp : AttrSafe p A) : AttrSafe (fst >>> p) (fun S (z : Value (.prod a b)) => A S z.1) := by obtain ⟨f,hf⟩ := hp refine ⟨.add .input f,fun O S x hx => ?_⟩ have hw := (width_fst (a:=a) (b:=b) x).trans hx.1 apply safe_compose O fst p x · exact ⟨hx.1.trans (Nat.le_add_right _ _),fun y hy => by cases hy; exact hw.trans (Nat.le_add_right _ _),trivial⟩ · intro y hy cases hy exact safe_mono p x.1 (hf O S x.1 ⟨hw,hx.2⟩) (Nat.le_add_left _ _) lemma attrSafe_snd {a b c : DataType} (p : Expression b c) (A : Attribute b) (hp : AttrSafe p A) : AttrSafe (snd >>> p) (fun S (z : Value (.prod a b)) => A S z.2) := by obtain ⟨f,hf⟩ := hp refine ⟨.add .input f,fun O S x hx => ?_⟩ have hw := (width_snd (a:=a) (b:=b) x).trans hx.1 apply safe_compose O snd p x · exact ⟨hx.1.trans (Nat.le_add_right _ _),fun y hy => by cases hy; exact hw.trans (Nat.le_add_right _ _),trivial⟩ · intro y hy cases hy exact safe_mono p x.2 (hf O S x.2 ⟨hw,hx.2⟩) (Nat.le_add_left _ _) lemma attrSafe_shift {a b : DataType} (p : Expression a b) (A : Attribute a) (hp : AttrSafe p A) : AttrSafe p (fun S x => A (S+1) x) := by apply polySafe_mono p (polySafe_reparam p _ hp (.add .input (.constant 1))) intro S x hx exact ⟨hx.1.trans (Nat.le_add_right S 1),hx.2⟩ lemma attr_anneal : AttrSafe annealCode weightAttr := polySafe_mono annealCode polySafe_anneal (by intro S x hx; exact ⟨hx.1,hx.2.1,hx.2.2⟩) lemma attr_weightedPlain : AttrSafe weightedPlainCode (fun S z => z.1≤S) := by unfold weightedPlainCode apply attrSafe_applyIf _ _ _ _ (by intro S T h z hz; exact hz.trans h) (attrSafe_controlled _ (by have h := controlled_plainCode; cc) _) (attrSafe_controlled _ (by cc) _) apply attrSafe_pull _ annealCode _ (fun S z => weightAttr (S+1) z) (by cc) (attrSafe_shift _ _ attr_anneal) · intro S T h z hz exact weightAttr_mono _ _ (Nat.add_le_add_right h 1) z hz · intro n O S z hz y hy cases hy exact ⟨hz.trans (Nat.le_add_right S 1),Nat.le_add_left 1 S⟩ lemma attr_weightedList : AttrSafe weightedListCode (fun S z => z.1≤S) := by unfold weightedListCode apply attrSafe_pull _ _ _ (fun S (z : Value (.prod SampleData .nat)) => ∀ x∈z.1,z.2≤S) (by cc) · apply attrSafe_mapWith _ (fun S (z : Value (.prod StateData .nat)) => z.2≤S) (by intro S T h z hz; exact hz.trans h) apply attrSafe_pull _ _ _ (fun S (z : Value (.prod .nat StateData)) => z.1≤S) (by cc) attr_weightedPlain · intro S T h z hz; exact hz.trans h · intro n O S z hz y hy; cases hy; exact hz · intro S T h z hz x hx; exact (hz x hx).trans h · intro n O S z hz y hy; cases hy; exact fun _ _ => hz lemma controlled_plainMean : Controlled plainMeanCode := by have h := controlled_countPlain unfold plainMeanCode; cc lemma attr_weightedMean : AttrSafe weightedMeanCode (fun S z => z.1≤S) := by unfold weightedMeanCode Expression.letIn apply attrSafe_post · exact attrSafe_both _ _ _ (attrSafe_controlled _ (by cc) _) attr_weightedList · unfold natRatCode; cc lemma attr_ratio : AttrSafe ratioCode (fun S z => z.1≤S) := by unfold ratioCode exact attrSafe_post _ _ _ (attrSafe_both _ _ _ attr_weightedMean (attrSafe_controlled _ controlled_plainMean _)) controlled_ratDiv lemma controlled_historyAt : Controlled historyAtCode := by unfold historyAtCode; cc lemma attr_ratioAt : AttrSafe ratioAtCode (fun S z => z.2.1.1.2≤S) := by unfold ratioAtCode apply attrSafe_pull _ _ _ (fun S (z : Value (.prod .nat SampleData)) => z.1≤S) (by have h := controlled_historyAt; cc) attr_ratio · intro S T h z hz; exact hz.trans h · intro n O S z hz y hy have he : z.2.1.1.2=y.1 := Option.some.inj (run_both_parts O _ _ z y hy).1 exact he ▸ hz lemma attr_pow : AttrSafe Expression.powCode (fun S z => z.2≤S) := by apply polySafe_mono _ polySafe_powCode intro S z hz exact ⟨(width_fst (a:=.nat) (b:=.nat) z).trans hz.1,hz.2⟩ def estimatorAttr (S : ℕ) (z : Value PhaseInput) : Prop := z.1.1.1≤S ∧ z.1.1.2≤S ∧ z.1.2.1.2≤S lemma estimatorAttr_mono : Attribute.Mono (a:=PhaseInput) estimatorAttr := by intro S T h z hz; exact ⟨hz.1.trans h,hz.2.1.trans h,hz.2.2.trans h⟩ lemma attr_estimate : AttrSafe estimateCode estimatorAttr := by unfold estimateCode apply attrSafe_post · apply attrSafe_both · apply attrSafe_pull _ _ _ (fun S (z : Value (.prod .nat .nat)) => z.2≤S) (by cc) · exact attrSafe_post _ _ _ attr_pow (by unfold natRatCode; cc) · intro S T h z hz; exact hz.trans h · intro n O S z hz y hy; cases hy; exact hz.1 · apply attrSafe_compose _ _ _ (fun S (z : Value (.prod (.list .nat) PhaseInput)) => ∀ i∈z.1,z.2.1.1.2≤S) · apply attrSafe_both · apply attrSafe_mono _ (attrSafe_fst _ _ (attrSafe_snd _ _ (attrSafe_fst _ _ (attrSafe_snd _ _ attr_rangeCode)))) intro S z hz; exact hz.2.2 · exact attrSafe_controlled _ (by cc) _ · apply attrSafe_post _ _ _ _ controlled_ratProduct exact attrSafe_mapWith _ (fun S (z : Value (.prod .nat PhaseInput)) => z.2.1.1.2≤S) (by intro S T h z hz; exact hz.trans h) attr_ratioAt · intro S T h z hz i hi; exact (hz i hi).trans h · intro n O S z hz y hy have he : z=y.2 := Option.some.inj (run_both_parts O _ _ z y hy).2 intro i hi rw [←he]; exact hz.2.1 · exact controlled_ratMul lemma attr_guard : AttrSafe guardCode (fun S z => estimatorAttr S z.1) := by unfold guardCode apply attrSafe_applyIf _ _ _ _ (fun S T h (z : Value (.prod PhaseInput StateData)) hz => estimatorAttr_mono S T h z.1 hz) (attrSafe_controlled _ (by cc) _) (attrSafe_controlled _ (by cc) _) apply attrSafe_pull fst _ _ estimatorAttr (by cc) attr_estimate estimatorAttr_mono intro n O S z hz y hy; cases hy; exact hz open Expression Effect lemma oracleSafe_optionMap {a b : DataType} (p : Expression a b) (R : OraclePredicate a) (hp : OracleSafe p R) : OracleSafe (optionMapCode p) (optionScope R) := by obtain ⟨f,hf⟩ := oracleSafe_input_bound p R hp let W : SizePolynomial := .add f (.constant (width (zeroValue a)+3)) have hw : ∀ n O S x,optionScope R n O S x → width x≤W.eval S := optionScope_width R f hf unfold optionMapCode apply oracleSafe_applyIf _ _ _ (optionScope R) · exact oracleSafe_controlled _ (by cc) _ W hw · exact oracleSafe_controlled _ (by cc) _ W (by intro n O S x hx; exact hw n O S x hx.1) · apply oracleSafe_both · exact oracleSafe_controlled _ (by cc) _ W (by intro n O S x hx; exact hw n O S x hx.1) · apply oracleSafe_pull snd p _ R (by cc) W (by intro n O S x hx; exact hw n O S x hx.1) hp intro n O S x hx y hy cases hy have hv : x.1=true := Option.some.inj hx.2 rcases hx.1 with hz | ⟨_,hr⟩ · rw [hz] at hv; cases hv · exact hr open Expression open scoped Classical namespace Effect lemma safe_guard : OracleSafe guardCode phaseStateScope := by apply oracleSafe_attr _ _ (fun S T h (z : Value (.prod PhaseInput StateData)) hz => estimatorAttr_mono S T h z.1 hz) attr_guard phaseStateScope _ phaseStateScope_width intro n O S z hz obtain ⟨m,hm,h,hh,x,rfl⟩ := hz exact ⟨hm.1,hm.2.1,hm.2.2.2.1⟩ lemma safe_finalGuard : OracleSafe finalGuardCode (bankScope phaseScope) := by unfold finalGuardCode map apply oracleSafe_bind _ _ phaseScope (optionScope phaseStateScope) (oracleSafe_retainOption _ _ safe_witness) (oracleSafe_pure _ _ (oracleSafe_optionMap _ _ safe_guard)) intro n O S z bank hz hb y rest hy obtain ⟨m,hm,h,hh,rfl⟩ := hz have hl := law_retainOption O witnessCode (fun x : PlainIndex (pairedSlots n) => stateEncode x.val.val) (m.phaseValue h) _ (witnessCode_source m.M₁ m.M₂ O m.exact m.ground₁ m.ground₂ m.rank m.samples m.phases h m.positive) obtain ⟨v,he,hr⟩ := hl.output_some bank y rest hy refine ⟨?_,hr.trans hb⟩ rw [he] apply optionScope_encode intro x exact ⟨m,hm,h,hh,x.val,rfl⟩ lemma safe_algorithm : OracleSafe algorithmCode (bankScope algorithmScope) := by unfold algorithmCode apply oracleSafe_optionBind _ _ algorithmScope phaseScope safe_algorithmHistory safe_finalGuard intro n O S z bank hz hb y rest hy obtain ⟨m,hm,rfl⟩ := hz have hl := algorithmHistoryCode_source m.M₁ m.M₂ O m.exact m.ground₁ m.ground₂ m.rank m.samples m.phases m.positive have ha := history_length (canonicalPhaseTree n m.positive m.rank O m.samples m.phases) m.phases ([] : m.Hist) obtain ⟨v,he,hv,hr⟩ := hl.output_some_all _ ha bank y rest hy refine ⟨?_,hr.trans hb⟩ rw [he] cases v with | none => exact Or.inl rfl | some h => have hh : h.length≤S := by have he := hv h rfl simp only [List.length_nil,Nat.zero_add] at he exact he.le.trans hm.2.2.2.1 exact Or.inr ⟨rfl,m,hm,h,hh,rfl⟩ end Effect open Expression lemma oracleSafe_mapStep {a b c : DataType} (p : Expression (.prod a c) b) (Q : OraclePredicate (.prod a c)) (hp : OracleSafe p Q) (g : SizePolynomial) : OracleSafe (mapStep p) (fun n O S z => width z≤g.eval S ∧ Q n O S (z.1,z.2.2)) := by let R : OraclePredicate (.prod a (.prod (.list b) c)) := fun n O S z => width z≤g.eval S ∧ Q n O S (z.1,z.2.2) have hc : ∀ {d} (q : Expression (.prod a (.prod (.list b) c)) d),Controlled q → OracleSafe q R := fun q hq => oracleSafe_controlled q hq R g (by intro n O S z hz; exact hz.1) unfold mapStep apply oracleSafe_both · apply oracleSafe_post _ _ R _ (by cc) apply oracleSafe_both · apply oracleSafe_pull _ p R Q (by cc) g (by intro n O S z hz; exact hz.1) hp intro n O S z hz y hy; cases hy; exact hz.2 · exact hc _ (by cc) · exact hc _ (by cc) lemma oracleSafe_mapFold {a b c : DataType} (p : Expression (.prod a c) b) (Q : OraclePredicate (.prod a c)) (hp : OracleSafe p Q) (g : SizePolynomial) : OracleSafe (.fold (mapStep p)) (fun n O S z => width z≤g.eval S ∧ ∀ x∈z.1,Q n O S (x,z.2.2)) := by obtain ⟨f,hf⟩ := hp let U : SizePolynomial := .mul (.add (.mul (.constant 4) g) (.constant 3)) (.add (.mul (.constant 2) f) (.constant 3)) have hacc : ∀ {n : ℕ} (O : IndependenceOracle n) S xs zs ctx, width (a:=.prod (.list a) (.prod (.list b) c)) (xs,(zs,ctx))≤g.eval S → (∀ x∈xs,Q n O S (x,ctx)) → ∀ pre post,xs=pre++post → ∀ y, foldValue (run O (mapStep p)) pre (zs,ctx)=some y → width y≤U.eval S ∧ y.2=ctx := by intro n O S xs zs ctx hw ha pre post he y hy have hx : width (a:=.list a) xs≤g.eval S := (width_fst _).trans hw have hzs : width (a:=.list b) zs≤g.eval S := (width_fst (a:=.list b) (b:=c) (zs,ctx)).trans ((width_snd _).trans hw) have hc : width ctx≤g.eval S := (width_snd (a:=.list b) (b:=c) (zs,ctx)).trans ((width_snd _).trans hw) have hl : pre.length≤g.eval S := by have hh := (list_length_le_width xs).trans hx rw [he,List.length_append] at hh; omega have hh := fold_mapStep_bound O p pre zs ctx (f.eval S) (by intro x hxp v hv exact safe_output (hf O S (x,ctx) (ha x (by rw [he]; exact List.mem_append_left post hxp))) hv) y hy have hm := Nat.mul_le_mul_right (2*f.eval S+2) hl have hy' : width (a:=.list b) y.1≤g.eval S+g.eval S*(2*f.eval S+2) := by omega refine ⟨?_,hh.2⟩ have hw' : width y=2*width (a:=.list b) y.1+1+width ctx := by rw [width_pair (a:=.list b) (b:=c),hh.2] rw [hw'] simp only [U,SizePolynomial.eval] nlinarith let W : SizePolynomial := .add (.mul (.constant 3) g) (.add U (.constant 1)) apply oracleSafe_fold (mapStep p) _ (fun n O S (z : Value (.prod a (.prod (.list b) c))) => width z≤W.eval S ∧ Q n O S (z.1,z.2.2)) (oracleSafe_mapStep p Q ⟨f,hf⟩ W) (.add g U) · intro n O S z hz; exact hz.1.trans (Nat.le_add_right _ _) · intro n O S xs z hz pre post he y hy exact (hacc O S xs z.1 z.2 hz.1 hz.2 pre post he y hy).1.trans (Nat.le_add_left _ _) · intro n O S xs z hz pre x post he y hy have hh := hacc O S xs z.1 z.2 hz.1 hz.2 pre (x::post) he y hy have hm : x∈xs := by rw [he]; simp have hx := (width_list_member x xs hm).trans ((width_fst _).trans hz.1) refine ⟨?_,?_⟩ · rw [width_pair (a:=a) (b:=.prod (.list b) c)] change _≤3*g.eval S+(U.eval S+1); omega · rw [hh.2]; exact hz.2 x hm lemma oracleSafe_mapWith {a b c : DataType} (p : Expression (.prod a c) b) (Q : OraclePredicate (.prod a c)) (hp : OracleSafe p Q) (g : SizePolynomial) : OracleSafe (mapWith p) (fun n O S z => width z≤g.eval S ∧ ∀ x∈z.1,Q n O S (x,z.2)) := by let R : OraclePredicate (.prod (.list a) c) := fun n O S z => width z≤g.eval S ∧ ∀ x∈z.1,Q n O S (x,z.2) let prep : Expression (.prod (.list a) c) (.prod (.list a) (.prod (.list b) c)) := both fst (both (constant []) snd) have hprep : OracleSafe prep R := oracleSafe_controlled prep (by dsimp [prep]; cc) R g (by intro n O S z hz; exact hz.1) obtain ⟨f,hf⟩ := hprep unfold mapWith apply oracleSafe_compose _ _ R (fun n O S (z : Value (.prod (.list a) (.prod (.list b) c))) => width z≤f.eval S ∧ ∀ x∈z.1,Q n O S (x,z.2.2)) ⟨f,hf⟩ · exact oracleSafe_post _ _ _ (oracleSafe_mapFold p Q hp f) (by cc) · intro n O S z hz y hy refine ⟨safe_output (hf O S z hz) hy,?_⟩ cases hy; exact hz.2 namespace Expression abbrev InsertState := DataType.prod NN (.prod (.list NN) (.list NN)) def insertStep : Expression (.prod NN InsertState) InsertState := both (snd >>> fst) (both (both fst (snd >>> snd >>> fst) >>> Expression.cons) (applyIf (both fst (snd >>> fst) >>> ratLess) (both (snd >>> fst) (both fst (snd >>> snd >>> fst) >>> Expression.cons) >>> Expression.cons) (both fst (snd >>> snd >>> snd) >>> Expression.cons))) def insertInit : Expression (.prod NN (.list NN)) InsertState := both fst (both (constant (b:=.list NN) []) (both fst (constant (b:=.list NN) []) >>> Expression.cons (a:=NN))) def insertRatCode : Expression (.prod NN (.list NN)) (.list NN) := both (snd >>> listReverse) insertInit >>> fold insertStep >>> snd >>> snd def sortRatCode : Expression (.list NN) (.list NN) := both listReverse (constant []) >>> fold insertRatCode def medianCode : Expression (.list NN) NN := both (both sortRatCode (listLength >>> both (constant 2) ident >>> natDiv)) (constant (0,1)) >>> getDCode lemma run_insertStep {n : ℕ} (O : IndependenceOracle n) (q x : ℚ) (hq : 0≤q) (hx : 0≤x) (xs ys : List ℚ) : run O insertStep (rationalPair x,(rationalPair q,(xs.map rationalPair,ys.map rationalPair)))= some (rationalPair q,((x::xs).map rationalPair, (if x simp [h,run] lemma run_insertRatCode {n : ℕ} (O : IndependenceOracle n) (q : ℚ) (hq : 0≤q) (xs : List ℚ) (hx : ∀ x∈xs,0≤x) : run O insertRatCode (rationalPair q,xs.map rationalPair)= some ((xs.orderedInsert (·≤·) q).map rationalPair) := by have hf : ∀ xs : List ℚ,(∀x∈xs,0≤x) → foldValue (run O insertStep) (xs.map rationalPair).reverse (rationalPair q,([], [rationalPair q]))= some (rationalPair q,(xs.map rationalPair,(xs.orderedInsert (·≤·) q).map rationalPair)) := by intro xs induction xs with | nil => intro hx; rfl | cons x xs ih => intro hx simp only [List.map_cons,List.reverse_cons,foldValue_append] rw [ih (fun y hy => hx y (by simp [hy])),Option.bind_some,foldValue] rw [run_insertStep O q x hq (hx x (by simp)),Option.bind_some] simp only [foldValue,List.orderedInsert_cons] by_cases h : x some z.2.2)=_ rw [hf xs hx] rfl lemma run_sortRatCode {n : ℕ} (O : IndependenceOracle n) (xs : List ℚ) (hx : ∀ x∈xs,0≤x) : run O sortRatCode (xs.map rationalPair)=some ((xs.mergeSort (·≤·)).map rationalPair) := by have hf : ∀ xs : List ℚ,(∀x∈xs,0≤x) → foldValue (run O insertRatCode) (xs.map rationalPair).reverse []= some ((xs.insertionSort (·≤·)).map rationalPair) := by intro xs induction xs with | nil => intro hx; rfl | cons x xs ih => intro hx simp only [List.map_cons,List.reverse_cons,foldValue_append] rw [ih (fun y hy => hx y (by simp [hy])),Option.bind_some,foldValue] rw [run_insertRatCode O x (hx x (by simp)) _ (by intro y hy exact hx y (by simpa using Or.inr ((List.perm_insertionSort _ _).mem_iff.mp hy)))] rfl simp only [sortRatCode,run_compose,run_both,run_constant,run_listReverse,Option.bind_some,Option.map_some] change foldValue (run O insertRatCode) (xs.map rationalPair).reverse []=_ rw [hf xs hx,List.mergeSort_eq_insertionSort] lemma run_medianCode {n : ℕ} (O : IndependenceOracle n) (xs : List ℚ) (hx : ∀ x∈xs,0≤x) : run O medianCode (xs.map rationalPair)=some (rationalPair (rationalMedian xs)) := by simp only [medianCode,run_compose,run_both,run_ident,run_constant] rw [run_sortRatCode O xs hx] simp only [Option.bind_some,Option.map_some] rw [run_listLength] simp only [Option.bind_some,List.length_map] simp only [run_compose,run_both,run_constant,run_ident,Option.bind_some,Option.map_some] rw [run_natDiv] simp only [Option.bind_some,Option.map_some] rw [run_getDCode] unfold rationalMedian simp only [List.getD_eq_getElem?_getD,List.getElem?_map] cases (xs.mergeSort (·≤·))[xs.length/2]? <;> rfl end Expression lemma run_insertStep_raw {n : ℕ} (O : IndependenceOracle n) (x q : Value NN) (xs ys : List (Value NN)) : run O insertStep (x,(q,(xs,ys)))= some (q,(x::xs,if x.1*q.2 rfl lemma insertFold_width {n : ℕ} (O : IndependenceOracle n) (xs : List (Value NN)) (q : Value NN) (zs ys : List (Value NN)) (y : Value InsertState) (hy : foldValue (run O insertStep) xs (q,(zs,ys))=some y) : y.1=q ∧ width (a:=.list NN) y.2.1=width (a:=.list NN) zs+width (a:=.list NN) xs ∧ width (a:=.list NN) y.2.2≤ max (width (a:=.list NN) ys) (2*width (a:=NN) q+2+width (a:=.list NN) zs)+width (a:=.list NN) xs := by induction xs generalizing zs ys with | nil => cases hy; exact ⟨rfl,by rw [width_nil,Nat.add_zero],by rw [width_nil,Nat.add_zero]; exact Nat.le_max_left _ _⟩ | cons x xs ih => rw [foldValue,run_insertStep_raw,Option.bind_some] at hy have hh := ih (x::zs) (if x.1*q.2 simp only [width_cons (a:=NN)] at hh ⊢ <;> omega lemma controlled_insertStep : Controlled insertStep := by unfold insertStep; cc lemma controlled_insertFold : Controlled (.fold insertStep) := by apply controlled_fold _ controlled_insertStep (.add (.mul (.constant 5) .input) (.constant 5)) intro n O xs z pre post he y hy obtain ⟨q,zs,ys⟩ := z have hh := insertFold_width O pre q zs ys y hy have hp : width (a:=.list NN) pre≤width (a:=.list NN) xs := by rw [he,width_list_append]; omega rw [width_pair (a:=NN) (b:=.prod (.list NN) (.list NN)),hh.1, width_pair (a:=.list NN) (b:=.list NN),hh.2.1] change 2*width (a:=NN) q+1+(2*(width (a:=.list NN) zs+width (a:=.list NN) pre)+1+width (a:=.list NN) y.2.2)≤5*width (a:=.prod (.list NN) InsertState) (xs,(q,(zs,ys)))+5 rw [width_pair (a:=.list NN) (b:=InsertState),width_pair (a:=NN) (b:=.prod (.list NN) (.list NN)), width_pair (a:=.list NN) (b:=.list NN)] omega lemma controlled_insertRat : Controlled insertRatCode := by have hi := controlled_insertFold unfold insertRatCode insertInit; cc lemma insertRat_width {n : ℕ} (O : IndependenceOracle n) (q : Value NN) (xs ys : List (Value NN)) (hy : run O insertRatCode (q,xs)=some ys) : width (a:=.list NN) ys≤width (a:=.list NN) xs+2*(2*width (a:=NN) q+2) := by simp only [insertRatCode,insertInit,run_compose,run_both,run_fst,run_snd,run_constant, Option.bind_some,Option.map_some,run_listReverse] at hy change ((foldValue (run O insertStep) xs.reverse (q,([],[q]))).bind fun z => some z.2.2)=some ys at hy cases he : foldValue (run O insertStep) xs.reverse (q,([],[q])) with | none => simp [he] at hy | some v => simp only [he,Option.bind_some,Option.some.injEq] at hy subst ys have hh := (insertFold_width O xs.reverse q [] [q] v he).2.2 simp only [width_nil (a:=NN),width_cons (a:=NN),width_list_reverse (a:=NN)] at hh omega lemma sortFold_width {n : ℕ} (O : IndependenceOracle n) (xs zs ys : List (Value NN)) (hy : foldValue (run O insertRatCode) xs zs=some ys) : width (a:=.list NN) ys≤width (a:=.list NN) zs+2*width (a:=.list NN) xs := by induction xs generalizing zs with | nil => cases hy; simp | cons x xs ih => rw [foldValue] at hy cases he : run O insertRatCode (x,zs) with | none => simp [he] at hy | some v => simp only [he,Option.bind_some] at hy have hv := insertRat_width O x zs v he have hh := ih v hy rw [width_cons] omega lemma controlled_sortFold : Controlled (.fold insertRatCode) := by apply controlled_fold _ controlled_insertRat (.mul (.constant 3) .input) intro n O xs zs pre post he ys hy have hh := sortFold_width O pre zs ys hy have hp : width (a:=.list NN) pre≤width (a:=.list NN) xs := by rw [he,width_list_append]; omega change _≤3*width (a:=.prod (.list NN) (.list NN)) (xs,zs) rw [width_pair (a:=.list NN) (b:=.list NN)] omega lemma controlled_sortRat : Controlled sortRatCode := by have hi := controlled_sortFold unfold sortRatCode; cc lemma controlled_median : Controlled medianCode := by have hi := controlled_sortRat unfold medianCode; cc namespace Expression def optionalRatCode : Expression (Optional NN) NN := applyIf fst (constant (0,1)) snd def singleCode : Expression (.prod AlgorithmParams BankData) NN := Effect.algorithmCode >>> fst >>> applyIf fst (constant (0,1)) (snd >>> optionalRatCode) def amplifiedCode : Expression (.prod AlgorithmParams (.list BankData)) NN := swap >>> mapWith (swap >>> singleCode) >>> medianCode lemma run_optionalRatCode {n : ℕ} (O : IndependenceOracle n) (x : Option ℚ) : run O optionalRatCode (optionEncode rationalPair x)=some (rationalPair (x.getD 0)) := by cases x <;> rfl lemma run_singleCode {n : ℕ} (O : IndependenceOracle n) (x : Value AlgorithmParams) (t : DrawTree (Option ℚ)) (ht : Effect.Realizes O Effect.algorithmCode (optionEncode rationalPair) x t) (bank : Bank) : run O singleCode (x,bank)=some (rationalPair ((bankEval t bank).1.join.getD 0)) := by rw [singleCode,run_compose,ht,Option.bind_some] cases h : (bankEval t bank).1 with | none => rfl | some v => cases v <;> rfl lemma run_amplifiedCode {n : ℕ} (O : IndependenceOracle n) (x : Value AlgorithmParams) (t : DrawTree (Option ℚ)) (ht : Effect.Realizes O Effect.algorithmCode (optionEncode rationalPair) x t) (banks : List Bank) (hz : ∀ bank∈banks,0≤(bankEval t bank).1.join.getD 0) : run O amplifiedCode (x,banks)= some (rationalPair (rationalMedian (banks.map (fun bank => (bankEval t bank).1.join.getD 0)))) := by simp only [amplifiedCode,run_compose] change ((run O (mapWith (swap >>> singleCode)) (banks,x)).bind (run O medianCode))=_ have hm := run_mapWith_source O (swap >>> singleCode) (fun bank : Bank => bank) (fun bank => rationalPair ((bankEval t bank).1.join.getD 0)) x (fun bank => by change run O singleCode (x,bank)=_; exact run_singleCode O x t ht bank) banks simp only [List.map_id_fun',id_eq] at hm rw [hm] simp only [Option.bind_some] rw [show banks.map (fun bank => rationalPair ((bankEval t bank).1.join.getD 0))= (banks.map (fun bank => (bankEval t bank).1.join.getD 0)).map rationalPair by simp only [List.map_map]; rfl] apply run_medianCode intro q hq obtain ⟨bank,hbank,rfl⟩ := List.mem_map.mp hq exact hz bank hbank end Expression open Expression Effect lemma safe_single : OracleSafe singleCode (bankScope algorithmScope) := by unfold singleCode exact oracleSafe_post _ _ _ safe_algorithm (by unfold optionalRatCode; cc) def amplificationScope : OraclePredicate (.prod AlgorithmParams (.list BankData)) := fun n O S z => algorithmScope n O S z.1 ∧ width (a:=.list BankData) z.2≤S lemma amplificationScope_width : ∀ n O S z,amplificationScope n O S z → width z≤(.add (.mul (.constant 2) (sourceWidthPoly 100)) (.add .input (.constant 1)) : SizePolynomial).eval S := by intro n O S z hz have hp := algorithmScope_width n O S z.1 hz.1 have hb := hz.2 rw [width_pair (a:=AlgorithmParams) (b:=.list BankData)] change _≤2*(sourceWidthPoly 100).eval S+(S+1) omega lemma safe_amplified : OracleSafe amplifiedCode amplificationScope := by let Q : OraclePredicate (.prod BankData AlgorithmParams) := fun n O S z => bankScope algorithmScope n O S (z.2,z.1) let W : SizePolynomial := .add (.mul (.constant 2) .input) (.add (.constant 1) (sourceWidthPoly 100)) have hq : OracleSafe (Expression.swap >>> singleCode) Q := by refine oracleSafe_pull Expression.swap singleCode Q (bankScope algorithmScope) (by cc) W ?_ safe_single ?_ · intro n O S z hz have hp := algorithmScope_width n O S z.2 hz.1 have hb : width (a:=BankData) z.1≤S := hz.2 rw [width_pair (a:=BankData) (b:=AlgorithmParams)] change 2*width (a:=BankData) z.1+1+width (a:=AlgorithmParams) z.2≤2*S+(1+(sourceWidthPoly 100).eval S) omega · intro n O S z hz y hy; cases hy; exact hz let T : OraclePredicate (.prod (.list BankData) AlgorithmParams) := fun n O S z => width z≤W.eval S ∧ ∀ bank∈z.1,Q n O S (bank,z.2) unfold amplifiedCode apply oracleSafe_pull Expression.swap _ amplificationScope T (by cc) _ amplificationScope_width (oracleSafe_post _ _ _ (oracleSafe_mapWith _ Q hq W) controlled_median) intro n O S z hz y hy cases hy refine ⟨?_,?_⟩ · have hp := algorithmScope_width n O S z.1 hz.1 have hb := hz.2 rw [width_pair (a:=.list BankData) (b:=AlgorithmParams)] change _≤2*S+(1+(sourceWidthPoly 100).eval S) omega · intro bank hb exact ⟨hz.1,(width_list_member bank z.2 hb).trans hz.2⟩ open Expression abbrev FrozenData := DataType.prod NN (.prod NN NN) def frozenValue (n r : ℕ) (ε δ : ℚ) : Value FrozenData := ((n,r),((ε.num.natAbs,ε.den),(δ.num.natAbs,δ.den))) namespace Expression def natPow : ℕ → Expression .nat .nat | 0 => constant 1 | k+1 => both ident (natPow k) >>> mul lemma run_natPow {n : ℕ} (O : IndependenceOracle n) (k x : ℕ) : run O (natPow k) x=some (x^k) := by induction k with | zero => rfl | succ k ih => simp [natPow,run_compose,ih,run,pow_succ,Nat.mul_comm] lemma controlled_natPow (k : ℕ) : Controlled (natPow k) := by induction k with | zero => unfold natPow; cc | succ k ih => unfold natPow; cc def sumE {a} (p q : Expression a .nat) : Expression a .nat := both p q >>> add def prodE {a} (p q : Expression a .nat) : Expression a .nat := both p q >>> mul lemma run_sumE {n : ℕ} (O : IndependenceOracle n) {a} (p q : Expression a .nat) (x : Value a) (u v : ℕ) (hp : run O p x=some u) (hq : run O q x=some v) : run O (sumE p q) x=some (u+v) := by simp [sumE,run_compose,hp,hq,run] lemma run_prodE {n : ℕ} (O : IndependenceOracle n) {a} (p q : Expression a .nat) (x : Value a) (u v : ℕ) (hp : run O p x=some u) (hq : run O q x=some v) : run O (prodE p q) x=some (u*v) := by simp [prodE,run_compose,hp,hq,run] lemma controlled_sumE {a} (p q : Expression a .nat) (hp : Controlled p) (hq : Controlled q) : Controlled (sumE p q) := by unfold sumE; cc lemma controlled_prodE {a} (p q : Expression a .nat) (hp : Controlled p) (hq : Controlled q) : Controlled (prodE p q) := by unfold prodE; cc def ceilDivCode : Expression NN .nat := both fst (both (sumE snd fst) (constant 1) >>> natSub) >>> divRem >>> snd lemma run_ceilDivCode {n : ℕ} (O : IndependenceOracle n) (a b : ℕ) (ha : 0>> toList >>> listLength lemma run_lengthNatCode {n : ℕ} (O : IndependenceOracle n) (x : ℕ) : run O lengthNatCode x=some x.bits.length := by change run O (listLength (a:=.bool)) x.bits=_ exact run_listLength O _ lemma controlled_lengthNatCode : Controlled lengthNatCode := by unfold lengthNatCode have h := controlled_listLength (a:=.bool) cc def annealLengthCode : Expression NN .nat := prodE (prodE (constant 2) fst) (sumE fst (sumE snd (constant 5))) lemma run_annealLengthCode {n : ℕ} (O : IndependenceOracle n) (x e : ℕ) : run O annealLengthCode (x,e)=some (2*x*(x+(e+5))) := by simp [annealLengthCode,prodE,sumE,run_compose,run] lemma controlled_annealLengthCode : Controlled annealLengthCode := by unfold annealLengthCode prodE sumE; cc def sampleCountCode : Expression (.prod .nat NN) .nat := sumE (prodE (prodE (prodE (constant (10^14)) (sumE (snd >>> fst) (constant 1) >>> natPow 3)) (fst >>> natPow 14)) (snd >>> snd >>> natPow 2)) (constant 1) lemma run_sampleCountCode {n : ℕ} (O : IndependenceOracle n) (x L E : ℕ) : run O sampleCountCode (x,(L,E))=some (10^14*(L+1)^3*x^14*E^2+1) := by simp only [sampleCountCode,prodE,sumE,run_compose,run_both,run_constant,run_fst,run_snd, Option.bind_some,Option.map_some,run_natPow] rfl lemma controlled_sampleCountCode : Controlled sampleCountCode := by unfold sampleCountCode apply controlled_sumE · apply controlled_prodE · apply controlled_prodE · apply controlled_prodE · cc · apply controlled_compose · apply controlled_sumE <;> cc · exact controlled_natPow 3 · apply controlled_compose · cc · exact controlled_natPow 14 · apply controlled_compose · cc · apply controlled_compose · cc · exact controlled_natPow 2 · cc def tauCode : Expression NN .nat := prodE (prodE (constant 20) (fst >>> natPow 4)) (sumE (prodE fst (sumE snd (constant 1))) (constant 2)) def capCode : Expression NN .nat := prodE (prodE (prodE (constant 2000) (sumE snd (constant 1) >>> natPow 2)) (fst >>> natPow 2)) tauCode lemma run_tauCode {n : ℕ} (O : IndependenceOracle n) (x L : ℕ) : run O tauCode (x,L)=some (20*x^4*(x*(L+1)+2)) := by simp only [tauCode,prodE,sumE,run_compose,run_both,run_constant,run_fst,run_snd, Option.bind_some,Option.map_some,run_natPow] rfl lemma run_capCode {n : ℕ} (O : IndependenceOracle n) (x L : ℕ) : run O capCode (x,L)=some (restartCap x L) := by simp only [capCode,prodE,sumE,run_compose,run_both,run_constant,run_fst,run_snd, Option.bind_some,Option.map_some,run_natPow] simp only [run,Option.bind_some,Option.map_some] rw [run_tauCode] rfl lemma controlled_tauCode : Controlled tauCode := by unfold tauCode prodE sumE have h4 := controlled_natPow 4 cc lemma controlled_capCode : Controlled capCode := by unfold capCode prodE sumE have h2 := controlled_natPow 2 have ht := controlled_tauCode cc def chunkValues {α : Type*} (m h : ℕ) (xs : List α) : List (List α) := (List.range m).map (fun i => (xs.drop (i*h)).take h) def chunkStep {a : DataType} : Expression (.prod .nat (.prod (.list a) .nat)) (.list a) := both (both (snd >>> fst) (prodE fst (snd >>> snd)) >>> dropCode) (snd >>> snd) >>> takeCode def chunksCode {a : DataType} : Expression (.prod (.list a) NN) (.list (.list a)) := both ((snd >>> fst) >>> rangeCode) (both fst (snd >>> snd)) >>> mapWith chunkStep lemma run_chunkStep {n : ℕ} (O : IndependenceOracle n) {a : DataType} (i h : ℕ) (xs : List (Value a)) : run O chunkStep (i,(xs,h))=some ((xs.drop (i*h)).take h) := by simp only [chunkStep,prodE,run_compose,run_both,run_fst,run_snd,Option.bind_some,Option.map_some] simp only [run,Option.map_some,Option.bind_some] rw [run_dropCode,Option.bind_some,Option.bind_some,run_takeCode] lemma run_chunksCode {n : ℕ} (O : IndependenceOracle n) {a : DataType} (xs : List (Value a)) (m h : ℕ) : run O chunksCode (xs,(m,h))=some (chunkValues m h xs) := by simp only [chunksCode,run_compose,run_both,run_fst,run_snd,Option.bind_some,Option.map_some] rw [run_rangeCode,Option.bind_some,Option.bind_some] exact run_mapWith O chunkStep (fun i ctx => (ctx.1.drop (i*ctx.2)).take ctx.2) (fun i ctx => run_chunkStep O i ctx.2 ctx.1) _ _ lemma chunkValues_zero {α : Type*} (h : ℕ) (xs : List α) : chunkValues 0 h xs=[] := rfl lemma chunkValues_succ {α : Type*} (m h : ℕ) (xs : List α) : chunkValues (m+1) h xs=xs.take h::chunkValues m h (xs.drop h) := by simp only [chunkValues,List.range_succ_eq_map,List.map_cons,List.map_map,Nat.zero_mul,List.drop_zero] congr 1 apply List.map_congr_left intro i hi simp only [Function.comp_apply,Nat.succ_eq_add_one,List.drop_drop,Nat.add_mul,Nat.one_mul,Nat.add_comm h] lemma chunkValues_flatten {α : Type*} (h : ℕ) (xs : List (List α)) (hx : ∀ x∈xs,x.length=h) : chunkValues xs.length h xs.flatten=xs := by induction xs with | nil => rfl | cons x xs ih => have hh := hx x (by simp) have ht := ih (fun y hy => hx y (by simp [hy])) rw [List.length_cons,chunkValues_succ,List.flatten_cons,←hh,List.take_left,List.drop_left,hh,ht] lemma chunkValues_ofFn {α : Type*} (m h : ℕ) (f : Fin m → Fin h → α) : chunkValues m h ((List.ofFn (fun i => List.ofFn (f i))).flatten)= List.ofFn (fun i => List.ofFn (f i)) := by convert chunkValues_flatten h (List.ofFn (fun i => List.ofFn (f i))) (by intro xs hx obtain ⟨i,rfl⟩ := List.mem_ofFn.mp hx exact List.length_ofFn) using 1 ; simp end Expression lemma controlled_chunkStep {a : DataType} : Controlled (chunkStep (a:=a)) := by unfold chunkStep prodE cc lemma attr_chunksCode {a : DataType} : AttrSafe (chunksCode (a:=a)) (fun S x => x.2.1≤S) := by unfold chunksCode apply attrSafe_post · apply attrSafe_both · apply attrSafe_pull _ rangeCode _ _ (by cc) attr_rangeCode (fun S T h k hk => hk.trans h) intro n O S x hx y hy cases hy; exact hx · exact attrSafe_controlled _ (by cc) _ · exact controlled_mapWith _ controlled_chunkStep lemma ceil_nat_ratio (a b : ℕ) (ha : 0 rw [←Rat.num_div_den ε,inv_div] open Expression Effect namespace Expression def frozenN : Expression FrozenData .nat := fst >>> fst def frozenL : Expression FrozenData .nat := both frozenN (snd >>> fst >>> snd >>> lengthNatCode) >>> annealLengthCode def frozenE : Expression FrozenData .nat := snd >>> fst >>> ceilDivCode def frozenSamples : Expression FrozenData .nat := both frozenN (both frozenL frozenE) >>> sampleCountCode def frozenParams : Expression FrozenData AlgorithmParams := both fst (both (both frozenSamples frozenL) (both (both frozenN frozenL >>> capCode) (both frozenN frozenL >>> tauCode))) def frozenReps : Expression FrozenData .nat := prodE (constant 64) (sumE (snd >>> snd >>> snd >>> lengthNatCode) (constant 1)) abbrev Recipe3 := DataType.prod .nat NN def drawsCode : Expression Recipe3 .nat := prodE (sumE (sumE (constant 1) (prodE (prodE (prodE (constant 3) (snd >>> snd)) (sumE (both fst (snd >>> snd) >>> capCode) (constant 1))) (both fst (snd >>> snd) >>> tauCode))) (prodE (constant 3) (snd >>> fst))) (sumE (snd >>> snd) (constant 1)) def wordBoundCode : Expression Recipe3 .nat := sumE (sumE (sumE (prodE (constant 2) (sumE (sumE (constant 2) (prodE (snd >>> fst) (snd >>> snd))) (prodE (prodE (constant 2) fst) (prodE fst (snd >>> snd))))) (fst >>> natPow 2)) fst) (constant 4) def frozenRecipe3 : Expression FrozenData Recipe3 := both frozenN (both frozenSamples frozenL) def frozenDraws : Expression FrozenData .nat := frozenRecipe3 >>> drawsCode def frozenWordBound : Expression FrozenData .nat := frozenRecipe3 >>> wordBoundCode abbrev BankShape := DataType.prod .nat NN abbrev PreparedData := DataType.prod AlgorithmParams BankShape def frozenPrepared : Expression FrozenData PreparedData := both frozenParams (both frozenReps (both frozenDraws frozenWordBound)) def bitCountCode : Expression BankShape .nat := prodE (prodE (prodE fst (snd >>> snd)) (sumE (snd >>> fst) (constant 6))) (snd >>> fst) def frozenBitCount : Expression FrozenData .nat := frozenPrepared >>> snd >>> bitCountCode lemma run_frozenN {n : ℕ} (O : IndependenceOracle n) (r : ℕ) (ε δ : ℚ) : run O frozenN (frozenValue n r ε δ)=some n := rfl lemma run_frozenL {n : ℕ} (O : IndependenceOracle n) (r : ℕ) (ε δ : ℚ) : run O frozenL (frozenValue n r ε δ)=some (annealLength n (accuracyExponent ε)) := by simp only [frozenL,frozenN,run_compose,run_both,run_fst,run_snd,Option.bind_some,frozenValue] rw [run_lengthNatCode,Option.map_some,Option.bind_some,run_annealLengthCode] rfl lemma run_frozenE {n : ℕ} (O : IndependenceOracle n) (r : ℕ) (ε δ : ℚ) (hε : 0<ε) : run O frozenE (frozenValue n r ε δ)=some ⌈ε⁻¹⌉₊ := by change run O ceilDivCode (ε.num.natAbs,ε.den)=_ rw [run_ceilDivCode O _ _ (Int.natAbs_pos.mpr (ne_of_gt (Rat.num_pos.mpr hε))),inverse_ceiling_input ε hε] lemma run_frozenSamples {n : ℕ} (O : IndependenceOracle n) (r : ℕ) (ε δ : ℚ) (hε : 0<ε) : run O frozenSamples (frozenValue n r ε δ)=some (sampleCount n (annealLength n (accuracyExponent ε)) ε) := by simp only [frozenSamples,run_compose,run_both,run_frozenN,run_frozenL,run_frozenE O r ε δ hε,Option.bind_some,Option.map_some] rw [run_sampleCountCode]; rfl lemma run_frozenParams {n : ℕ} (O : IndependenceOracle n) (r : ℕ) (ε δ : ℚ) (hε : 0<ε) : run O frozenParams (frozenValue n r ε δ)=some (params n r (sampleCount n (annealLength n (accuracyExponent ε)) ε) (annealLength n (accuracyExponent ε))) := by simp only [frozenParams,run_both,run_compose,run_fst,run_frozenN,run_frozenL,run_frozenSamples O r ε δ hε,Option.bind_some,Option.map_some] rw [run_capCode,run_tauCode]; rfl lemma run_frozenReps {n : ℕ} (O : IndependenceOracle n) (r : ℕ) (ε δ : ℚ) : run O frozenReps (frozenValue n r ε δ)=some (repetitionCount δ) := by simp only [frozenReps,prodE,sumE,run_compose,run_both,run_constant,run_snd,Option.bind_some,Option.map_some,frozenValue] rw [run_lengthNatCode]; rfl lemma run_drawsCode {n : ℕ} (O : IndependenceOracle n) (x N L : ℕ) : run O drawsCode (x,(N,L))=some (algorithmDrawBound x N L) := by simp only [drawsCode,prodE,sumE,run_compose,run_both,run_constant,run_fst,run_snd,Option.bind_some,Option.map_some] rw [run_capCode O,run_tauCode O] rfl lemma run_wordBoundCode {n : ℕ} (O : IndependenceOracle n) (x N L : ℕ) : run O wordBoundCode (x,(N,L))=some (drawWordBound x N L) := by simp only [wordBoundCode,prodE,sumE,run_compose,run_both,run_constant,run_fst,run_snd,Option.bind_some,Option.map_some,run_natPow] rfl lemma run_frozenRecipe3 {n : ℕ} (O : IndependenceOracle n) (r : ℕ) (ε δ : ℚ) (hε : 0<ε) : run O frozenRecipe3 (frozenValue n r ε δ)=some (n,(sampleCount n (annealLength n (accuracyExponent ε)) ε,annealLength n (accuracyExponent ε))) := by simp only [frozenRecipe3,run_both,run_frozenN,run_frozenL,run_frozenSamples O r ε δ hε,Option.bind_some,Option.map_some] lemma run_frozenPrepared {n : ℕ} (O : IndependenceOracle n) (r : ℕ) (ε δ : ℚ) (hε : 0<ε) : let L := annealLength n (accuracyExponent ε) let N := sampleCount n L ε run O frozenPrepared (frozenValue n r ε δ)=some (params n r N L,(repetitionCount δ,(algorithmDrawBound n N L,drawWordBound n N L))) := by simp only [frozenPrepared,frozenDraws,frozenWordBound,run_both,run_compose,run_frozenParams O r ε δ hε,run_frozenReps,run_frozenRecipe3 O r ε δ hε,Option.bind_some] rw [run_drawsCode O,run_wordBoundCode O] rfl lemma run_bitCountCode {n : ℕ} (O : IndependenceOracle n) (R M H : ℕ) : run O bitCountCode (R,(M,H))=some (R*H*(M+6)*M) := by simp only [bitCountCode,prodE,sumE,run_compose,run_both,run_constant,run_fst,run_snd,Option.bind_some,Option.map_some] rfl lemma run_frozenBitCount {n : ℕ} (O : IndependenceOracle n) (r : ℕ) (ε δ : ℚ) (hε : 0<ε) : run O frozenBitCount (frozenValue n r ε δ)=some (fairBitCount n ε δ) := by simp only [frozenBitCount,run_compose,run_frozenPrepared O r ε δ hε,run_snd,Option.bind_some] rfl lemma controlled_frozenN : Controlled frozenN := by unfold frozenN; cc lemma controlled_frozenL : Controlled frozenL := by unfold frozenL have hn := controlled_frozenN have hl := controlled_lengthNatCode have ha := controlled_annealLengthCode cc lemma controlled_frozenE : Controlled frozenE := by unfold frozenE have h := controlled_ceilDivCode cc lemma controlled_frozenSamples : Controlled frozenSamples := by unfold frozenSamples have hn := controlled_frozenN have hl := controlled_frozenL have he := controlled_frozenE have hs := controlled_sampleCountCode cc lemma controlled_frozenParams : Controlled frozenParams := by unfold frozenParams have hn := controlled_frozenN have hl := controlled_frozenL have hs := controlled_frozenSamples have hc := controlled_capCode have ht := controlled_tauCode cc lemma controlled_frozenReps : Controlled frozenReps := by unfold frozenReps prodE sumE have h := controlled_lengthNatCode cc lemma controlled_drawsCode : Controlled drawsCode := by unfold drawsCode prodE sumE have hc := controlled_capCode have ht := controlled_tauCode cc lemma controlled_wordBoundCode : Controlled wordBoundCode := by unfold wordBoundCode prodE sumE have h := controlled_natPow 2 cc lemma controlled_frozenRecipe3 : Controlled frozenRecipe3 := by unfold frozenRecipe3 have hn := controlled_frozenN have hl := controlled_frozenL have hs := controlled_frozenSamples cc lemma controlled_frozenPrepared : Controlled frozenPrepared := by unfold frozenPrepared frozenDraws frozenWordBound have hp := controlled_frozenParams have hr := controlled_frozenReps have h3 := controlled_frozenRecipe3 have hd := controlled_drawsCode have hw := controlled_wordBoundCode cc lemma controlled_bitCountCode : Controlled bitCountCode := by unfold bitCountCode prodE sumE; cc lemma controlled_frozenBitCount : Controlled frozenBitCount := by unfold frozenBitCount have hp := controlled_frozenPrepared have hb := controlled_bitCountCode cc abbrev Shape3 := DataType.prod .nat NN abbrev Shape4 := DataType.prod .nat Shape3 def rowsCode : Expression (.prod (.list .bool) NN) RandomRows := chunksCode >>> mapEach fromList def bankCode : Expression (.prod (.list .bool) Shape3) BankData := both (both fst (both (snd >>> fst) (prodE (snd >>> snd >>> fst) (snd >>> snd >>> snd))) >>> chunksCode) (snd >>> snd) >>> mapWith rowsCode def banksCode : Expression (.prod (.list .bool) Shape4) (.list BankData) := both (both fst (both (snd >>> fst) (prodE (snd >>> snd >>> fst) (prodE (snd >>> snd >>> snd >>> fst) (snd >>> snd >>> snd >>> snd)))) >>> chunksCode) (snd >>> snd) >>> mapWith bankCode def shape4Code : Expression BankShape Shape4 := both fst (both (snd >>> fst) (both (sumE (snd >>> fst) (constant 6)) (snd >>> snd))) def reshapeCode : Expression (.prod .word BankShape) (.list BankData) := both (fst >>> toList) (snd >>> shape4Code) >>> banksCode lemma run_rowsCode {n : ℕ} (O : IndependenceOracle n) (xs : List Bool) (D H : ℕ) : run O rowsCode (xs,(D,H))=some (chunkValues D H xs) := by rw [rowsCode,run_compose,run_chunksCode,Option.bind_some] simpa using run_mapEach O fromList (fun x => x) (run_fromList O) (chunkValues D H xs) lemma run_bankCode {n : ℕ} (O : IndependenceOracle n) (xs : List Bool) (M D H : ℕ) : run O bankCode (xs,(M,(D,H)))= some ((chunkValues M (D*H) xs).map (chunkValues D H)) := by simp only [bankCode,prodE,run_compose,run_both,run_fst,run_snd,Option.bind_some,Option.map_some] simp only [run,Option.map_some,Option.bind_some,Option.bind_assoc] change ((run O chunksCode (xs,(M,D*H))).bind fun ys => run O (mapWith rowsCode) (ys,(D,H)))=_ rw [run_chunksCode,Option.bind_some] exact run_mapWith O rowsCode (fun ys ctx => chunkValues ctx.1 ctx.2 ys) (fun ys ctx => run_rowsCode O ys ctx.1 ctx.2) _ _ lemma run_banksCode {n : ℕ} (O : IndependenceOracle n) (xs : List Bool) (R M D H : ℕ) : run O banksCode (xs,(R,(M,(D,H))))= some ((chunkValues R (M*(D*H)) xs).map (fun ys => (chunkValues M (D*H) ys).map (chunkValues D H))) := by simp only [banksCode,prodE,run_compose,run_both,run_fst,run_snd,Option.bind_some,Option.map_some] simp only [run,Option.map_some,Option.bind_some,Option.bind_assoc] change ((run O chunksCode (xs,(R,M*(D*H)))).bind fun ys => run O (mapWith bankCode) (ys,(M,(D,H))))=_ rw [run_chunksCode,Option.bind_some] exact run_mapWith O bankCode (fun ys ctx => (chunkValues ctx.1 (ctx.2.1*ctx.2.2) ys).map (chunkValues ctx.2.1 ctx.2.2)) (fun ys ctx => run_bankCode O ys ctx.1 ctx.2.1 ctx.2.2) _ _ lemma run_shape4Code {n : ℕ} (O : IndependenceOracle n) (R M H : ℕ) : run O shape4Code (R,(M,H))=some (R,(M,(M+6,H))) := rfl lemma controlled_shape4Code : Controlled shape4Code := by unfold shape4Code sumE; cc lemma attr_rowsCode : AttrSafe rowsCode (fun S z => z.2.1≤S) := by unfold rowsCode exact attrSafe_post _ _ _ attr_chunksCode (controlled_mapEach _ controlled_fromList) lemma attr_bankCode : AttrSafe bankCode (fun S z => z.2.1≤S ∧ z.2.2.1≤S) := by let A : Attribute (.prod (.list (.list .bool)) NN) := fun S z => z.2.1≤S have hm : A.Mono := by intro S T h z hz; exact hz.trans h unfold bankCode refine attrSafe_compose _ _ _ A ?_ ?_ hm ?_ · apply attrSafe_both · apply attrSafe_pull _ chunksCode _ _ (by unfold prodE; cc) attr_chunksCode (fun S T h z hz => hz.trans h) intro n O S z hz y hy cases hy; exact hz.1 · exact attrSafe_controlled _ (by cc) _ · apply attrSafe_mono _ (attrSafe_mapWith rowsCode (fun S z => z.2.1≤S) (fun S T h z hz => hz.trans h) attr_rowsCode) intro S z hz xs hxs; exact hz · intro n O S z hz y hy have he := (run_both_parts O _ _ z y hy).2 have he' : z.2.2=y.2 := Option.some.inj he dsimp only [A] rw [←he'] exact hz.2 lemma attr_banksCode : AttrSafe banksCode (fun S z => z.2.1≤S ∧ z.2.2.1≤S ∧ z.2.2.2.1≤S) := by let A : Attribute (.prod (.list (.list .bool)) Shape3) := fun S z => z.2.1≤S ∧ z.2.2.1≤S have hm : A.Mono := by intro S T h z hz; exact ⟨hz.1.trans h,hz.2.trans h⟩ unfold banksCode refine attrSafe_compose _ _ _ A ?_ ?_ hm ?_ · apply attrSafe_both · apply attrSafe_pull _ chunksCode _ _ (by unfold prodE; cc) attr_chunksCode (fun S T h z hz => hz.trans h) intro n O S z hz y hy cases hy; exact hz.1 · exact attrSafe_controlled _ (by cc) _ · apply attrSafe_mono _ (attrSafe_mapWith bankCode (fun S z => z.2.1≤S ∧ z.2.2.1≤S) (fun S T h z hz => ⟨hz.1.trans h,hz.2.trans h⟩) attr_bankCode) intro S z hz xs hxs; exact hz · intro n O S z hz y hy have he := (run_both_parts O _ _ z y hy).2 have he' : z.2.2=y.2 := Option.some.inj he dsimp only [A] rw [←he'] exact hz.2 lemma attr_reshapeCode : AttrSafe reshapeCode (fun S z => z.2.1≤S ∧ z.2.2.1+6≤S) := by unfold reshapeCode apply attrSafe_pull _ banksCode _ _ (by have h := controlled_shape4Code; cc) attr_banksCode (fun S T h z hz => ⟨hz.1.trans h,hz.2.1.trans h,hz.2.2.trans h⟩) intro n O S z hz y hy cases hy exact ⟨hz.1,(Nat.le_add_right _ 6).trans hz.2,hz.2⟩ def preambleCode : Expression FrozenData (.prod .word PreparedData) := both (frozenBitCount >>> unary) frozenPrepared abbrev RawData := DataType.prod .word PreparedData abbrev AmplifyInput := DataType.prod AlgorithmParams (.list BankData) def reshapePrepared : Expression RawData AmplifyInput := both (snd >>> fst) (both fst (snd >>> snd) >>> reshapeCode) def finishCode : Expression AmplifyInput NN := applyIf (fst >>> fst >>> fst >>> natEqZero) amplifiedCode (constant (1,1)) def postambleCode : Expression RawData NN := reshapePrepared >>> finishCode end Expression lemma safe_preamble : OracleSafe preambleCode (fun _ O S x => width x≤S ∧ ∀ k,run O frozenBitCount x=some k → k≤S) := by unfold preambleCode apply oracleSafe_both · apply oracleSafe_compose _ unary _ (fun _ _ S k => k≤S) (oracleSafe_controlled _ controlled_frozenBitCount _ .input (by intro n O S x hx; exact hx.1)) (oracleSafe_lift _ _ polySafe_unary) intro n O S x hx k hk; exact hx.2 k hk · exact oracleSafe_controlled _ controlled_frozenPrepared _ .input (by intro n O S x hx; exact hx.1) def rawScope : OraclePredicate RawData := fun n O S z => width z≤S ∧ z.2.2.1≤S ∧ z.2.2.2.1+6≤S ∧ z.2.1.1.1=n ∧ (0 z.2.2.1≤S ∧ z.2.2.2.1+6≤S) (fun S T h z hz => ⟨hz.1.trans h,hz.2.trans h⟩) ?_ rawScope .input (by intro n O S z hz; exact hz.1) (by intro n O S z hz; exact ⟨hz.2.1,hz.2.2.1⟩) apply attrSafe_pull _ reshapeCode _ _ (by cc) attr_reshapeCode (fun S T h z hz => ⟨hz.1.trans h,hz.2.trans h⟩) intro n O S z hz y hy; cases hy; exact hz def finishScope : OraclePredicate AmplifyInput := fun n O S z => width z≤S ∧ z.1.1.1=n ∧ (0 finishScope n O (g.eval S) z) ⟨f,hf⟩ (oracleSafe_reparam _ _ safe_finish g) intro n O S z hz y hy have he : z.2.1=y.1 := Option.some.inj (run_both_parts O _ _ z y hy).1 refine ⟨(safe_output (hf O S z hz) hy).trans (Nat.le_add_right _ _),?_,?_⟩ · rw [←he]; exact hz.2.2.2.1 · intro hn rw [←he] exact algorithmScope_mono (hz.2.2.2.2 hn) (Nat.le_add_left _ _) def coinPush {k : ℕ} (a : Fin (k+8)) : Block k := fork .coin (push a false) (push a true) lemma runs_coinPush {k n : ℕ} (O : IndependenceOracle n) (bits : ℕ → Bool) (R : Registers k) (a : Fin (k+8)) : Runs (coinPush a) O bits R (Function.update R a (bits 0::R a)) 2 0 2 := by cases h : bits 0 · exact fork_run_no .coin _ _ O bits (by simp [Test.result,h]) (runs_push O (fun i => bits (1+i)) R a false) · exact fork_run_yes .coin _ _ O bits (by simp [Test.result,h]) (runs_push O (fun i => bits (1+i)) R a true) def sampledWord : ℕ → (ℕ → Bool) → Word | 0,_ => [] | m+1,bits => sampledWord m (fun i => bits (3+i)) ++ [bits 1] lemma sampledWord_length (m : ℕ) (bits : ℕ → Bool) : (sampledWord m bits).length=m := by induction m generalizing bits with | zero => rfl | succ m ih => simp [sampledWord,ih] lemma sampledWord_get (m : ℕ) (bits : ℕ → Bool) (i : ℕ) (hi : i < m) : (sampledWord m bits)[i]'(by rw [sampledWord_length]; exact hi)= bits (3*(m-1-i)+1) := by induction m generalizing bits i with | zero => omega | succ m ih => by_cases him : i < m · simp only [sampledWord] rw [List.getElem_append_left (by rw [sampledWord_length]; exact him),ih _ _ him] congr 1 omega · have he : i=m := by omega subst i simp [sampledWord,List.getElem_append_right,sampledWord_length] lemma sampledWord_ofFn (m : ℕ) (bits : ℕ → Bool) : sampledWord m bits=List.ofFn (fun i : Fin m => bits (3*(m-1-i.val)+1)) := by apply List.ext_getElem · simp [sampledWord_length] · intro i hi hj simp only [List.getElem_ofFn] exact sampledWord_get m bits i (by simpa [sampledWord_length] using hi) lemma runs_coinLoop {k n : ℕ} (O : IndependenceOracle n) (bits : ℕ → Bool) (R : Registers k) (a b : Fin (k+8)) (hab : a≠b) (xs : Word) : Runs (repeatBlock (coinPush b) a) O bits (Function.update R a xs) (Function.update (Function.update R b (sampledWord xs.length bits ++ R b)) a []) (3*xs.length+1) 0 (3*xs.length+1) := by induction xs generalizing R bits with | nil => intro q w have h := repeatProgram_empty (coinPush b).code a O R q w bits convert h using 1 <;> simp [repeatBlock,sampledWord,state,loopConfig] ; rfl | cons x xs ih => have hp := runs_coinPush O (fun i => bits (1+i)) (Function.update R a xs) b have hi := ih (fun i => bits (3+i)) (Function.update R b (bits 1::R b)) have hc : Function.update (Function.update R a xs) b (bits 1::(Function.update R a xs) b)= Function.update (Function.update R b (bits 1::R b)) a xs := by rw [Function.update_of_ne hab.symm] exact Function.update_comm hab .. rw [hc] at hp have h := runs_repeat_cons (b:=x) hp hi convert h using 1 <;> simp only [sampledWord,List.length_cons] · simp only [Function.update_self,List.append_assoc,List.singleton_append] rw [Function.update_idem] · omega · omega lemma runs_pack_any {k n : ℕ} (a d : Fin (k+8)) (had : a≠d) (O : IndependenceOracle n) (R : Registers k) (bits : ℕ → Bool) : Runs (pack a d) O bits R (Function.update (Function.update R a []) d (pair (R a) (R d))) (3*(R a).length+2) 0 (3*(R a).length+2) := by have h := runs_pack a d had O R (R a) (R d) bits have he : pairRegisters R a d (R a) (R d)=R := by simp [pairRegisters] rw [he] at h exact h lemma runs_move_any {k n : ℕ} (a b d : Fin (k+8)) (hab : a≠b) (had : a≠d) (hbd : b≠d) (O : IndependenceOracle n) (R : Registers k) (hb : R b=[]) (hd : R d=[]) (bits : ℕ → Bool) : Runs (move a b d) O bits R (Function.update (Function.update R a []) d (R a)) (4*(R a).length+2) 0 (4*(R a).length+2) := by have h := runs_move a b d hab had hbd O R (R a) [] bits have he : tripleRegisters R a b d (R a) [] []=R := by unfold tripleRegisters pairRegisters rw [Function.update_eq_self] have h1 : Function.update R b []=R := by rw [←hb, Function.update_eq_self] rw [h1] rw [←hd,Function.update_eq_self] rw [he] at h simp only [List.append_nil] at h convert h using 1 simp only [tripleRegisters, pairRegisters] rw [Function.update_comm hab,show Function.update R b []=R by rw [←hb,Function.update_eq_self]] def sixRegs (a b c d e f : Word) : Registers 1 := fun i => match i.val with | 0 => a | 1 => b | 2 => c | 3 => d | 4 => e | 5 => f | _ => [] def inputPack : Block 1 := seq (pack 4 5) (seq (pack 2 3) (seq (pack 3 5) (seq (pack 0 1) (seq (pack 1 5) (move 5 2 0))))) def inputTime (a b c d e f : Word) : ℕ := (3*e.length+2)+((3*c.length+2)+((3*(pair c d).length+2)+((3*a.length+2)+ ((3*(pair a b).length+2)+(4*(pair (pair a b) (pair (pair c d) (pair e f))).length+2))))) lemma runs_inputPack {n : ℕ} (O : IndependenceOracle n) (bits : ℕ → Bool) (a b c d e f : Word) : Runs inputPack O bits (sixRegs a b c d e f) (regs (pair (pair a b) (pair (pair c d) (pair e f))) [] [] []) (inputTime a b c d e f) 0 (inputTime a b c d e f) := by have h1 (bits) : Runs (pack 4 5) O bits (sixRegs a b c d e f) (sixRegs a b c d [] (pair e f)) (3*e.length+2) 0 (3*e.length+2) := by convert runs_pack_any (k:=1) 4 5 (by decide) O (sixRegs a b c d e f) bits using 1 all_goals first | rfl | (funext i; fin_cases i <;> simp [sixRegs]) have h2 (bits) : Runs (pack 2 3) O bits (sixRegs a b c d [] (pair e f)) (sixRegs a b [] (pair c d) [] (pair e f)) (3*c.length+2) 0 (3*c.length+2) := by convert runs_pack_any (k:=1) 2 3 (by decide) O (sixRegs a b c d [] (pair e f)) bits using 1 all_goals first | rfl | (funext i; fin_cases i <;> simp [sixRegs]) have h3 (bits) : Runs (pack 3 5) O bits (sixRegs a b [] (pair c d) [] (pair e f)) (sixRegs a b [] [] [] (pair (pair c d) (pair e f))) (3*(pair c d).length+2) 0 (3*(pair c d).length+2) := by convert runs_pack_any (k:=1) 3 5 (by decide) O (sixRegs a b [] (pair c d) [] (pair e f)) bits using 1 all_goals first | rfl | (funext i; fin_cases i <;> simp [sixRegs]) have h4 (bits) : Runs (pack 0 1) O bits (sixRegs a b [] [] [] (pair (pair c d) (pair e f))) (sixRegs [] (pair a b) [] [] [] (pair (pair c d) (pair e f))) (3*a.length+2) 0 (3*a.length+2) := by convert runs_pack_any (k:=1) 0 1 (by decide) O (sixRegs a b [] [] [] (pair (pair c d) (pair e f))) bits using 1 all_goals first | rfl | (funext i; fin_cases i <;> simp [sixRegs]) have h5 (bits) : Runs (pack 1 5) O bits (sixRegs [] (pair a b) [] [] [] (pair (pair c d) (pair e f))) (sixRegs [] [] [] [] [] (pair (pair a b) (pair (pair c d) (pair e f)))) (3*(pair a b).length+2) 0 (3*(pair a b).length+2) := by convert runs_pack_any (k:=1) 1 5 (by decide) O (sixRegs [] (pair a b) [] [] [] (pair (pair c d) (pair e f))) bits using 1 all_goals first | rfl | (funext i; fin_cases i <;> simp [sixRegs]) have h6 (bits) : Runs (move 5 2 0) O bits (sixRegs [] [] [] [] [] (pair (pair a b) (pair (pair c d) (pair e f)))) (regs (pair (pair a b) (pair (pair c d) (pair e f))) [] [] []) (4*(pair (pair a b) (pair (pair c d) (pair e f))).length+2) 0 (4*(pair (pair a b) (pair (pair c d) (pair e f))).length+2) := by convert runs_move_any (k:=1) 5 2 0 (by decide) (by decide) (by decide) O (sixRegs [] [] [] [] [] (pair (pair a b) (pair (pair c d) (pair e f)))) rfl rfl bits using 1 all_goals first | rfl | (funext i; fin_cases i <;> simp [sixRegs,regs]) exact runs_seq O bits (h1 _) (runs_seq O _ (h2 _) (runs_seq O _ (h3 _) (runs_seq O _ (h4 _) (runs_seq O _ (h5 _) (h6 _))))) lemma inputTime_bound (a b c d e f : Word) : inputTime a b c d e f≤100*(6+a.length+b.length+c.length+d.length+e.length+f.length) := by simp only [inputTime,pair_length] omega lemma frozen_width (n r : ℕ) (ε δ : ℚ) : width (frozenValue n r ε δ)≤4*inputLength n r ε δ := by simp only [width,frozenValue,encode,pair_length] unfold inputLength omega lemma initialConfig_state (s n r : ℕ) (ε δ : ℚ) : initialConfig 1 s n r ε δ=state (sixRegs n.bits r.bits ε.num.natAbs.bits ε.den.bits δ.num.natAbs.bits δ.den.bits) 0 0 0 := rfl open Expression def preparedValue (n r : ℕ) (ε δ : ℚ) : Value PreparedData := let L := annealLength n (accuracyExponent ε) let N := sampleCount n L ε (params n r N L,(repetitionCount δ,(algorithmDrawBound n N L,drawWordBound n N L))) def rawValue (n r : ℕ) (ε δ : ℚ) (w : BitWord (fairBitCount n ε δ)) : Value RawData := (List.ofFn w,preparedValue n r ε δ) open Expression namespace SizePolynomial def pow (p : SizePolynomial) : ℕ → SizePolynomial | 0 => .constant 1 | k+1 => .mul (pow p k) p lemma eval_pow (p : SizePolynomial) (k x : ℕ) : (p.pow k).eval x=(p.eval x)^k := by induction k with | zero => rfl | succ k ih => simp only [pow,eval,ih,pow_succ] end SizePolynomial def masterParameter (n r : ℕ) (ε δ : ℚ) : ℕ := 1+n+inputLength n r ε δ+⌈ε⁻¹⌉₊+Nat.clog 2 ⌈δ⁻¹⌉₊ def atomPoly : SizePolynomial := .mul (.constant (10^22)) (.pow (.add .input (.constant 1)) 24) def tauPoly : SizePolynomial := .mul (.mul (.constant 20) (atomPoly.pow 4)) (.add (.mul atomPoly (.add atomPoly (.constant 1))) (.constant 2)) def capPoly : SizePolynomial := .mul (.mul (.mul (.constant 2000) ((SizePolynomial.add atomPoly (.constant 1)).pow 2)) (atomPoly.pow 2)) tauPoly def fairPoly : SizePolynomial := .mul (.constant (10^66)) ((SizePolynomial.add .input (.constant 1)).pow 73) def sourceEnvelope : SizePolynomial := .add (.add (.add (.add atomPoly tauPoly) capPoly) fairPoly) (.constant 6) def scopeEnvelope : SizePolynomial := .mul (.constant 100) (.add sourceEnvelope (.constant 1)) lemma master_pos (n r : ℕ) (ε δ : ℚ) : 0 < masterParameter n r ε δ := by unfold masterParameter; omega lemma rank_le_ground {n r : ℕ} (M : Matroid (Fin n)) (hr : M.eRank=(r:ℕ∞)) : r ≤ n := by have h := M.eRank_le_encard_ground rw [hr] at h have hg : M.E.encard ≤ n := (Set.encard_mono (Set.subset_univ _)).trans_eq (by simp) exact_mod_cast h.trans hg lemma master_fields (n r : ℕ) (ε δ : ℚ) : n ≤ masterParameter n r ε δ ∧ inputLength n r ε δ ≤ masterParameter n r ε δ ∧ ε.den.bits.length ≤ masterParameter n r ε δ ∧ δ.den.bits.length ≤ masterParameter n r ε δ ∧ ⌈ε⁻¹⌉₊ ≤ masterParameter n r ε δ ∧ bitResourceParameter n ε δ ≤ masterParameter n r ε δ := by unfold masterParameter bitResourceParameter inputLength omega lemma atom_ge (T : ℕ) : T ≤ atomPoly.eval T ∧ 1 ≤ atomPoly.eval T := by simp only [atomPoly,SizePolynomial.eval,SizePolynomial.eval_pow] have h : T+1 ≤ (T+1)^24 := Nat.le_self_pow (by decide) _ constructor <;> omega lemma recipe_atom_bounds (n r : ℕ) (ε δ : ℚ) : let T := masterParameter n r ε δ let L := annealLength n (accuracyExponent ε) let N := sampleCount n L ε n ≤ atomPoly.eval T ∧ L ≤ atomPoly.eval T ∧ N ≤ atomPoly.eval T ∧ drawWordBound n N L ≤ atomPoly.eval T ∧ algorithmDrawBound n N L ≤ atomPoly.eval T ∧ repetitionCount δ ≤ atomPoly.eval T := by let T := masterParameter n r ε δ have hf := master_fields n r ε δ have hh := polynomial_recipe_bounds n ε.den.bits.length δ.den.bits.length ⌈ε⁻¹⌉₊ T (master_pos n r ε δ) hf.1 hf.2.2.1 hf.2.2.2.1 hf.2.2.2.2.1 have hp (k : ℕ) (hk : k ≤ 24) : T^k ≤ (T+1)^24 := (Nat.pow_le_pow_left (by omega : T ≤ T+1) k).trans (Nat.pow_le_pow_right (by omega : 1 ≤ T+1) hk) have h1 := hp 1 (by omega) simp only [pow_one] at h1 refine ⟨hf.1.trans (atom_ge T).1,?_,?_,?_,?_,?_⟩ all_goals simp only [atomPoly,SizePolynomial.eval_pow,SizePolynomial.eval] all_goals dsimp only [T] at h1 hp hh · exact hh.1.trans (by have h := hp 2 (by omega); omega) · exact hh.2.1.trans (by have h := hp 22 (by omega); omega) · exact hh.2.2.1.trans (by have h := hp 24 (by omega); omega) · exact hh.2.2.2.1.trans (by have h := hp 24 (by omega); omega) · exact hh.2.2.2.2.trans (by omega) lemma envelope_parameters (n r : ℕ) (ε δ : ℚ) (hr : r ≤ n) : let T := masterParameter n r ε δ let S := sourceEnvelope.eval T let L := annealLength n (accuracyExponent ε) let N := sampleCount n L ε n ≤ S ∧ r ≤ S ∧ N ≤ S ∧ L ≤ S ∧ restartCap n L ≤ S ∧ 20*n^4*(n*(L+1)+2) ≤ S ∧ repetitionCount δ ≤ S ∧ algorithmDrawBound n N L+6 ≤ S ∧ drawWordBound n N L ≤ S ∧ fairBitCount n ε δ ≤ S ∧ inputLength n r ε δ ≤ S := by let T := masterParameter n r ε δ let A := atomPoly.eval T let L := annealLength n (accuracyExponent ε) have hh := recipe_atom_bounds n r ε δ have ht : 20*n^4*(n*(L+1)+2) ≤ tauPoly.eval T := by simp only [tauPoly,SizePolynomial.eval,SizePolynomial.eval_pow] gcongr · exact hh.1 · exact hh.1 · exact hh.2.1 have hc : restartCap n L ≤ capPoly.eval T := by unfold restartCap simp only [capPoly,SizePolynomial.eval,SizePolynomial.eval_pow] gcongr <;> first | exact hh.2.1 | exact hh.1 have hb : fairBitCount n ε δ ≤ fairPoly.eval T := by apply (fairBitCount_polynomial n ε δ).trans simp only [fairPoly,SizePolynomial.eval,SizePolynomial.eval_pow] gcongr have hf := (master_fields n r ε δ).2.2.2.2.2 omega have hi : inputLength n r ε δ ≤ atomPoly.eval T := (master_fields n r ε δ).2.1.trans (atom_ge T).1 dsimp only [sourceEnvelope,SizePolynomial.eval] dsimp only at hh dsimp only [T,L] at ht hc hb hi exact ⟨by omega,by omega,by omega,by omega,by omega,by omega, by omega,by omega,by omega,by omega,by omega⟩ open Expression Effect lemma width_six (a b c d e f : ℕ) : width (a:=FrozenData) ((a,b),((c,d),(e,f)))= 4*a.bits.length+2*b.bits.length+4*c.bits.length+2*d.bits.length+ 2*e.bits.length+f.bits.length+7 := by rw [width_pair (a:=NN) (b:=.prod NN NN),width_pair (a:=NN) (b:=NN)] simp only [width_pair (a:=.nat) (b:=.nat),width_nat] omega lemma width_frozen (n r : ℕ) (ε δ : ℚ) : width (frozenValue n r ε δ)≤4*inputLength n r ε δ := by rw [frozenValue,width_six] unfold inputLength omega lemma width_prepared_bound (n r : ℕ) (ε δ : ℚ) (hr : r≤n) : width (preparedValue n r ε δ)≤35*sourceEnvelope.eval (masterParameter n r ε δ)+17 := by have hh := envelope_parameters n r ε δ hr dsimp only at hh have hn := (bits_length_le_value n).trans hh.1 have hr := (bits_length_le_value r).trans hh.2.1 have hN := (bits_length_le_value _).trans hh.2.2.1 have hL := (bits_length_le_value _).trans hh.2.2.2.1 have hc := (bits_length_le_value _).trans hh.2.2.2.2.1 have ht := (bits_length_le_value _).trans hh.2.2.2.2.2.1 have hR := (bits_length_le_value _).trans hh.2.2.2.2.2.2.1 have hM := (bits_length_le_value _).trans (show algorithmDrawBound n (sampleCount n (annealLength n (accuracyExponent ε)) ε) (annealLength n (accuracyExponent ε))≤ sourceEnvelope.eval (masterParameter n r ε δ) from by omega) have hH := (bits_length_le_value _).trans hh.2.2.2.2.2.2.2.2.1 rw [preparedValue,width_pair (a:=AlgorithmParams) (b:=BankShape),params,width_six, width_pair (a:=.nat) (b:=NN),width_pair (a:=.nat) (b:=.nat)] simp only [width_nat] omega lemma scopeEnvelope_ge (T : ℕ) : sourceEnvelope.eval T≤ scopeEnvelope.eval T := by simp only [scopeEnvelope,SizePolynomial.eval] omega lemma rawValue_scope {n : ℕ} (r : ℕ) (M₁ M₂ : Matroid (Fin n)) (O : IndependenceOracle n) (hO : ExactOracles M₁ M₂ O) (hE₁ : M₁.E=Set.univ) (hE₂ : M₂.E=Set.univ) (hr₁ : M₁.eRank=(r:ℕ∞)) (ε δ : ℚ) (w : BitWord (fairBitCount n ε δ)) : rawScope n O (scopeEnvelope.eval (masterParameter n r ε δ)) (rawValue n r ε δ w) := by have hr := rank_le_ground M₁ hr₁ have hs := scopeEnvelope_ge (masterParameter n r ε δ) have hh := envelope_parameters n r ε δ hr dsimp only at hh have hw := width_prepared_bound n r ε δ hr refine ⟨?_,hh.2.2.2.2.2.2.1.trans hs,hh.2.2.2.2.2.2.2.1.trans hs,rfl,?_⟩ · rw [rawValue,width_pair (a:=.word) (b:=PreparedData),width_word,List.length_ofFn] simp only [scopeEnvelope,SizePolynomial.eval] omega · intro hn let m : SamplerModel n O := ⟨M₁,M₂,hO,hE₁,hE₂,hn,r, sampleCount n (annealLength n (accuracyExponent ε)) ε,annealLength n (accuracyExponent ε)⟩ refine ⟨m,?_,rfl⟩ exact ⟨hh.1.trans hs,hh.2.1.trans hs,hh.2.2.1.trans hs,hh.2.2.2.1.trans hs, hh.2.2.2.2.1.trans hs,hh.2.2.2.2.2.1.trans hs⟩ lemma frozen_preamble_scope {n : ℕ} (O : IndependenceOracle n) (r : ℕ) (ε δ : ℚ) (hr : r≤n) (hε : 0<ε) : width (frozenValue n r ε δ)≤ scopeEnvelope.eval (masterParameter n r ε δ) ∧ ∀ k,run O frozenBitCount (frozenValue n r ε δ)=some k → k≤ scopeEnvelope.eval (masterParameter n r ε δ) := by have hh := envelope_parameters n r ε δ hr dsimp only at hh constructor · have hw := width_frozen n r ε δ simp only [scopeEnvelope,SizePolynomial.eval] omega · intro k hk rw [run_frozenBitCount O r ε δ hε,Option.some.injEq] at hk rw [←hk] exact hh.2.2.2.2.2.2.2.2.2.1.trans (scopeEnvelope_ge _) open Expression lemma compile_safe_bound {n : ℕ} (O : IndependenceOracle n) {a b : DataType} (p : Expression a b) (S : ℕ) (x : Value a) (y : Value b) (hs : Safe O S p x) (hr : run O p x=some y) : Bounded (compile p) O (encode x) (encode y) (chargeCoefficient p*(S+n+1)^chargeDegree p) := by rw [←evaluate_forget] at hr cases he : evaluate O p x with | none => simp [he] at hr | some v => rcases v with ⟨y',c⟩ simp only [he,Option.map_some,Option.some.injEq] at hr subst y' exact bounded_mono (compile_correct O p x y c he) (evaluate_polynomial O p S x y c hs he) def compiledMajorant {a b : DataType} (p : Expression a b) (f : SizePolynomial) : SizePolynomial := .mul (.constant (chargeCoefficient p)) ((SizePolynomial.add (.add f .input) (.constant 1)).pow (chargeDegree p)) lemma compile_majorant {n : ℕ} (O : IndependenceOracle n) {a b : DataType} (p : Expression a b) (f : SizePolynomial) (T : ℕ) (hn : n≤T) (x : Value a) (y : Value b) (hs : Safe O (f.eval T) p x) (hr : run O p x=some y) : Bounded (compile p) O (encode x) (encode y) ((compiledMajorant p f).eval T) := by apply bounded_mono (compile_safe_bound O p (f.eval T) x y hs hr) simp only [compiledMajorant,SizePolynomial.eval,SizePolynomial.eval_pow] gcongr lemma frozen_uniform_safe : ∃ fp fq : SizePolynomial, ∀ (n r : ℕ) (M₁ M₂ : Matroid (Fin n)) (O : IndependenceOracle n) (ε δ : ℚ), ExactOracles M₁ M₂ O → M₁.E=Set.univ → M₂.E=Set.univ → M₁.eRank=(r:ℕ∞) → 0<ε → Safe O (fp.eval (masterParameter n r ε δ)) preambleCode (frozenValue n r ε δ) ∧ ∀ w : BitWord (fairBitCount n ε δ), Safe O (fq.eval (masterParameter n r ε δ)) postambleCode (rawValue n r ε δ w) := by obtain ⟨fp,hp⟩ := safe_preamble obtain ⟨fq,hq⟩ := safe_postamble refine ⟨fp.subst scopeEnvelope,fq.subst scopeEnvelope,?_⟩ intro n r M₁ M₂ O ε δ hO hE₁ hE₂ hr hε simp only [SizePolynomial.eval_subst] refine ⟨hp O _ _ (frozen_preamble_scope O r ε δ (rank_le_ground M₁ hr) hε),?_⟩ intro w exact hq O _ _ (rawValue_scope r M₁ M₂ O hO hE₁ hE₂ hr ε δ w) lemma SizePolynomial.monomial_bound (p : SizePolynomial) (T : ℕ) (hT : 0 if i=6 then a else if i=7 then b else [] def outputPack : Block 1 := seq (unpack 0 6) (move 0 1 7) def outputTime (a b : Word) : ℕ := (3*a.length+1)+(4*b.length+2) lemma runs_outputPack {n : ℕ} (O : IndependenceOracle n) (bits : ℕ → Bool) (a b : Word) : Runs outputPack O bits (regs (pair a b) [] [] []) (outRegs a b) (outputTime a b) 0 (outputTime a b) := by let mid : Registers 1 := fun i => if i=0 then b else if i=6 then a else [] have h1 (bits) : Runs (unpack 0 6) O bits (regs (pair a b) [] [] []) mid (3*a.length+1) 0 (3*a.length+1) := by convert runs_unpack_packed (k:=1) 0 6 (by decide) O (fun _ => []) a b bits using 1 <;> funext i <;> fin_cases i <;> simp [pairRegisters,regs,mid,pair] have h2 (bits) : Runs (move 0 1 7) O bits mid (outRegs a b) (4*b.length+2) 0 (4*b.length+2) := by convert runs_move_any (k:=1) 0 1 7 (by decide) (by decide) (by decide) O mid (by simp [mid]) (by simp [mid]) bits using 1 all_goals first | rfl | (funext i; fin_cases i <;> simp [mid,outRegs]) exact runs_seq O bits (h1 _) (h2 _) lemma outputTime_bound (a b : Word) : outputTime a b≤4*(a.length+b.length)+3 := by unfold outputTime omega lemma runs_coinLoop_regs {n : ℕ} (O : IndependenceOracle n) (bits : ℕ → Bool) (x counter : Word) : Runs (repeatBlock (coinPush 2) 1) O bits (regs x counter [] []) (regs x [] (sampledWord counter.length bits) []) (3*counter.length+1) 0 (3*counter.length+1) := by have h := runs_coinLoop O bits (regs x [] [] []) 1 2 (by decide) counter simpa only [update_regs_one,update_regs_two,regs_two,List.append_nil] using h lemma runs_randomPack {n : ℕ} (O : IndependenceOracle n) (bits : ℕ → Bool) (p w : Word) : Runs (pack 2 0) O bits (regs p [] w []) (regs (pair w p) [] [] []) (3*w.length+2) 0 (3*w.length+2) := by simpa only [update_regs_zero,update_regs_two,regs_two,regs_zero] using runs_pack_any (k:=1) 2 0 (by decide) O (regs p [] w []) bits def pipeline (pre post : Block 1) : Block 1 := seq inputPack (seq pre (seq (unpack 0 1) (seq (repeatBlock (coinPush 2) 1) (seq (pack 2 0) (seq post outputPack))))) def pipelineTime (i pre f post a b : ℕ) : ℕ := i+(pre+((3*f+1)+((3*f+1)+((3*f+2)+(post+((3*a+1)+(4*b+2))))))) lemma runs_pipeline {n : ℕ} (O : IndependenceOracle n) (bits : ℕ → Bool) (a b c d e f : Word) (pre post : Block 1) (counter params x y : Word) (tp qp wp tq qq wq : ℕ) (hp : Computes pre O (pair (pair a b) (pair (pair c d) (pair e f))) (pair counter params) tp qp wp) (hq : Computes post O (pair (sampledWord counter.length (fun j => bits (inputTime a b c d e f+tp+(3*counter.length+1)+j))) params) (pair x y) tq qq wq) : Runs (pipeline pre post) O bits (sixRegs a b c d e f) (outRegs x y) (pipelineTime (inputTime a b c d e f) tp counter.length tq x.length y.length) (qp+qq) (pipelineTime (inputTime a b c d e f) wp counter.length wq x.length y.length) := by have h0 := runs_inputPack O bits a b c d e f have h1 := hp [] (fun j => bits (inputTime a b c d e f+j)) have h2 := split_pair O counter params [] [] (fun j => bits (inputTime a b c d e f+(tp+j))) simp only [List.append_nil] at h2 let bs := fun j => bits (inputTime a b c d e f+(tp+((3*counter.length+1)+j))) have h3 := runs_coinLoop_regs O bs params counter have h4 := runs_randomPack O (fun j => bs (3*counter.length+1+j)) params (sampledWord counter.length bs) have h5 := hq [] (fun j => bs (3*counter.length+1+(3*(sampledWord counter.length bs).length+2+j))) have he : (fun j => bits (inputTime a b c d e f+tp+(3*counter.length+1)+j))=bs := by funext j; dsimp [bs]; congr 1; omega rw [he] at h5 have h6 := runs_outputPack O (fun j => bs (3*counter.length+1+(3*(sampledWord counter.length bs).length+2+(tq+j)))) x y have h := runs_seq O bits h0 (runs_seq O _ h1 (runs_seq O _ h2 (runs_seq O _ h3 (runs_seq O _ h4 (runs_seq O _ h5 h6))))) simpa only [pipeline,pipelineTime,outputTime,sampledWord_length,Nat.zero_add,Nat.add_zero] using h def physicalWord (start m : ℕ) (bits : ℕ → Bool) : BitWord m := fun i => bits (start+3*(m-1-i.val)+1) lemma sampledWord_physical (start m : ℕ) (bits : ℕ → Bool) : sampledWord m (fun j => bits (start+j))=List.ofFn (physicalWord start m bits) := by rw [sampledWord_ofFn] apply congrArg List.ofFn funext i unfold physicalWord congr 1 def physicalPosition (start m B : ℕ) (h : start+3*m+1≤B) (i : Fin m) : Fin B := ⟨start+3*(m-1-i.val)+1,by have hi := i.isLt; omega⟩ lemma physicalPosition_injective (start m B : ℕ) (h : start+3*m+1≤B) : Function.Injective (physicalPosition start m B h) := by intro i j he have hh := congrArg Fin.val he dsimp only [physicalPosition] at hh apply Fin.ext have hi := i.isLt have hj := j.isLt omega lemma physicalWord_finite (start m B : ℕ) (h : start+3*m+1≤B) (w : BitWord B) : physicalWord start m (finiteBits w)=fun i => w (physicalPosition start m B h i) := by funext i unfold physicalWord finiteBits physicalPosition simp only [dite_eq_left (show start+3*(m-1-i.val)+1 φ (physicalWord start m (finiteBits w)))=uniformAverage φ := by simp_rw [physicalWord_finite start m B h] exact uniformAverage_bitEmbedding m B _ (physicalPosition_injective start m B h) φ def terminalState (p : Block 1) (x y : Word) (q w : ℕ) : MachineConfig 1 p.size := ⟨outRegs x y,lastLabel p.size,some ((binaryValue x:ℚ)/(binaryValue y:ℚ)),q,w+x.length+y.length+1⟩ lemma runs_terminal {n : ℕ} (p : Block 1) (O : IndependenceOracle n) (bits : ℕ → Bool) (R : Registers 1) (x y : Word) (t q w : ℕ) (h : Runs p O bits R (outRegs x y) t q w) : execution p.code O (state R 0 0 0) bits (t+1)=terminalState p x y q w := by rw [execution,h 0 0] simp only [Nat.zero_add] unfold machineStep state simp only [Option.isSome_none,Bool.false_eq_true,ite_false,p.exit_halt] simp only [outRegs,] rfl lemma input_state (s n r : ℕ) (ε δ : ℚ) : initialConfig 1 s n r ε δ=state (sixRegs n.bits r.bits ε.num.natAbs.bits ε.den.bits δ.num.natAbs.bits δ.den.bits) 0 0 0 := rfl lemma terminal_rational (p : Block 1) (z : ℚ) (hz : 0≤z) (q w : ℕ) : (terminalState p (rationalPair z).1.bits (rationalPair z).2.bits q w).output=some z := by change some ((binaryValue (rationalPair z).1.bits:ℚ)/(binaryValue (rationalPair z).2.bits:ℚ))=some z rw [binaryValue_bits,binaryValue_bits,rationalPair_value hz] def pipelineBudget (i F cp cq W : ℕ) : ℕ := i+cp+9*F+cq+5*W+10 lemma pipeline_budget (i F cp cq W tp qp wp tq qq wq a b : ℕ) (htp : tp≤cp) (hqp : qp≤cp) (hwp : wp≤cp) (htq : tq≤cq) (hqq : qq≤cq) (hwq : wq≤cq) (ho : 2*a+1+b≤W) : pipelineTime i tp F tq a b+1≤pipelineBudget i F cp cq W ∧ qp+qq≤pipelineBudget i F cp cq W ∧ pipelineTime i wp F wq a b+a+b+1≤pipelineBudget i F cp cq W ∧ i+tp+(3*F+1)+3*F+1≤pipelineBudget i F cp cq W := by unfold pipelineTime pipelineBudget omega lemma pipeline_budgeted {n : ℕ} (O : IndependenceOracle n) (a b c d e f : Word) (pre post : Block 1) (counter params : Word) (cp cq W B : ℕ) (hp : Bounded pre O (pair (pair a b) (pair (pair c d) (pair e f))) (pair counter params) cp) (v : BitWord counter.length → ℚ) (hv : ∀ w,0≤v w) (hq : ∀ w,Bounded post O (pair (List.ofFn w) params) (pair (rationalPair (v w)).1.bits (rationalPair (v w)).2.bits) cq ∧ 2*(rationalPair (v w)).1.bits.length+1+(rationalPair (v w)).2.bits.length≤W) (hB : pipelineBudget (inputTime a b c d e f) counter.length cp cq W≤B) : ∃ start,start+3*counter.length+1≤B ∧ ∀ bits : ℕ → Bool, let out := execution (pipeline pre post).code O (state (sixRegs a b c d e f) 0 0 0) bits B out.output=some (v (physicalWord start counter.length bits)) ∧ out.oracleCalls≤B ∧ out.bitOperations≤B := by obtain ⟨tp,qp,wp,htp,hqp,hwp,hp⟩ := hp let start := inputTime a b c d e f+tp+(3*counter.length+1) have hs : start+3*counter.length+1≤B := by apply le_trans _ hB unfold start pipelineBudget omega refine ⟨start,hs,?_⟩ intro bits let w := physicalWord start counter.length bits obtain ⟨⟨tq,qq,wq,htq,hqq,hwq,hq⟩,ho⟩ := hq w have hr := runs_pipeline O bits a b c d e f pre post counter params (rationalPair (v w)).1.bits (rationalPair (v w)).2.bits tp qp wp tq qq wq hp (by rw [sampledWord_physical]; exact hq) have hb := pipeline_budget (inputTime a b c d e f) counter.length cp cq W tp qp wp tq qq wq (rationalPair (v w)).1.bits.length (rationalPair (v w)).2.bits.length htp hqp hwp htq hqq hwq ho have ht := runs_terminal (pipeline pre post) O bits _ _ _ _ _ _ hr have hout := terminal_rational (pipeline pre post) (v w) (hv w) (qp+qq) (pipelineTime (inputTime a b c d e f) wp counter.length wq (rationalPair (v w)).1.bits.length (rationalPair (v w)).2.bits.length) have hsome : (execution (pipeline pre post).code O (state (sixRegs a b c d e f) 0 0 0) bits (pipelineTime (inputTime a b c d e f) tp counter.length tq (rationalPair (v w)).1.bits.length (rationalPair (v w)).2.bits.length+1)).output.isSome := by rw [ht,hout]; rfl have he := execution_extend_output (pipeline pre post).code O (state (sixRegs a b c d e f) 0 0 0) bits _ B (hb.1.trans hB) hsome dsimp only rw [he,ht] exact ⟨hout,hb.2.1.trans hB,hb.2.2.1.trans hB⟩ lemma pipeline_budgeted_length {n : ℕ} (O : IndependenceOracle n) (a b c d e f : Word) (pre post : Block 1) (counter params : Word) (F cp cq W B : ℕ) (hF : counter.length=F) (hp : Bounded pre O (pair (pair a b) (pair (pair c d) (pair e f))) (pair counter params) cp) (v : BitWord F → ℚ) (hv : ∀ w,0≤v w) (hq : ∀ w,Bounded post O (pair (List.ofFn w) params) (pair (rationalPair (v w)).1.bits (rationalPair (v w)).2.bits) cq ∧ 2*(rationalPair (v w)).1.bits.length+1+(rationalPair (v w)).2.bits.length≤W) (hB : pipelineBudget (inputTime a b c d e f) F cp cq W≤B) : ∃ start,start+3*F+1≤B ∧ ∀ bits : ℕ → Bool, let out := execution (pipeline pre post).code O (state (sixRegs a b c d e f) 0 0 0) bits B out.output=some (v (physicalWord start F bits)) ∧ out.oracleCalls≤B ∧ out.bitOperations≤B := by subst F exact pipeline_budgeted O a b c d e f pre post counter params cp cq W B hp v hv hq hB open Expression def totalResourcePoly (fp fq : SizePolynomial) : SizePolynomial := .mul (.constant 200) (.add (.add (.add sourceEnvelope (compiledMajorant preambleCode fp)) (compiledMajorant postambleCode fq)) (.add fq (.constant 1))) lemma totalResourcePoly_budget (fp fq : SizePolynomial) (n r : ℕ) (ε δ : ℚ) (hr : r≤n) : pipelineBudget (inputTime n.bits r.bits ε.num.natAbs.bits ε.den.bits δ.num.natAbs.bits δ.den.bits) (fairBitCount n ε δ) ((compiledMajorant preambleCode fp).eval (masterParameter n r ε δ)) ((compiledMajorant postambleCode fq).eval (masterParameter n r ε δ)) (fq.eval (masterParameter n r ε δ)) ≤ (totalResourcePoly fp fq).eval (masterParameter n r ε δ) := by have hi := inputTime_bound n.bits r.bits ε.num.natAbs.bits ε.den.bits δ.num.natAbs.bits δ.den.bits change _ ≤ 100*inputLength n r ε δ at hi have ha := envelope_parameters n r ε δ hr have hF := ha.2.2.2.2.2.2.2.2.2.1 have hI := ha.2.2.2.2.2.2.2.2.2.2 simp only [pipelineBudget,totalResourcePoly,SizePolynomial.eval] omega def fprasBlock : Block 1 := pipeline (compile preambleCode) (compile postambleCode) open Expression Effect open scoped Classical noncomputable def treeBankOutput (t : DrawTree (Option ℚ)) (bank : Bank) : ℚ := (bankEval t bank).1.join.getD 0 noncomputable def treeBanksOutput (t : DrawTree (Option ℚ)) (banks : List Bank) : ℚ := rationalMedian (banks.map (treeBankOutput t)) lemma treeBankOutput_all (t : DrawTree (Option ℚ)) (Z : ℕ) (ht : DrawTree.All (fun a : Option ℚ => ∀ z,a=some z → 0≤z ∧ (Z=0 → z=0)) t) (bank : Bank) : 0≤treeBankOutput t bank ∧ (Z=0 → treeBankOutput t bank=0) := by unfold treeBankOutput cases h : (bankEval t bank).1 with | none => simp | some a => cases a with | none => simp | some z => simpa only [Option.join_some,Option.getD_some] using bankEval_all t _ ht bank (some z) h z rfl lemma treeBanksOutput_all (t : DrawTree (Option ℚ)) (Z : ℕ) (ht : DrawTree.All (fun a : Option ℚ => ∀ z,a=some z → 0≤z ∧ (Z=0 → z=0)) t) (banks : List Bank) : 0≤treeBanksOutput t banks ∧ (Z=0 → treeBanksOutput t banks=0) := by constructor · apply rationalMedian_all (fun z => 0≤z) _ (by norm_num) intro z hz obtain ⟨bank,hbank,rfl⟩ := List.mem_map.mp hz exact (treeBankOutput_all t Z ht bank).1 · intro hZ apply rationalMedian_all (fun z => z=0) _ rfl intro z hz obtain ⟨bank,hbank,rfl⟩ := List.mem_map.mp hz exact (treeBankOutput_all t Z ht bank).2 hZ lemma reindexed_bank_law {t u : DrawTree (Option ℚ)} (h : DrawTree.Reindexed t u) (H D M : ℕ) (ht : DrawTree.Fits H M t) (φ : ℚ → ℝ) : uniformAverage (fun bits : Fin M → Fin D → BitWord H => φ (treeBankOutput u (bankEncode bits)))= uniformAverage (fun bits : Fin M → Fin D → BitWord H => φ ((DrawTree.run H D M t bits).join.getD 0)) := by unfold treeBankOutput simp only [bankEval_run H D M u (h.fits H M ht)] exact (h.run_observable H D M ht (fun a : Option (Option ℚ) => φ (a.join.getD 0))).symm lemma reindexed_banks_law {t u : DrawTree (Option ℚ)} (h : DrawTree.Reindexed t u) (H D M R : ℕ) (ht : DrawTree.Fits H M t) (φ : ℚ → ℝ) : uniformAverage (fun bits : Fin R → Fin M → Fin D → BitWord H => φ (treeBanksOutput u (List.ofFn (fun i => bankEncode (bits i)))))= uniformAverage (fun bits : Fin R → Fin M → Fin D → BitWord H => φ (rationalMedian (List.ofFn (fun i => (DrawTree.run H D M t (bits i)).join.getD 0)))) := by simp only [treeBanksOutput,List.map_ofFn,Function.comp_def] exact uniformAverage_independent_eq (fun bits => treeBankOutput u (bankEncode bits)) (fun bits => (DrawTree.run H D M t bits).join.getD 0) (reindexed_bank_law h H D M ht) R (fun z => φ (rationalMedian (List.ofFn z))) lemma canonicalTree_all {n : ℕ} (hn : 0 ∀ z,a=some z → 0≤z ∧ (commonBaseCount M₁ M₂=0 → z=0)) (canonicalAlgorithmTree n hn r O N L) := by apply DrawTree.All.mono ((canonicalAlgorithmTree_to_rational n hn r O N L M₁ M₂ hO hE₁ hE₂ hr₁ hr₂).symm.all _ (rationalAlgorithmTree_all n hn M₁ M₂ N L)) intro a ha z hz exact ⟨(ha z hz).1,(ha z hz).2 hE₂ (hr₁.trans hr₂.symm)⟩ open Expression lemma bitMatrix_apply (a b : ℕ) (w : BitWord (a*b)) (i : Fin a) (j : Fin b) : bitMatrixEquiv a b w i j=w (finProdFinEquiv (i,j)) := rfl lemma ofFn_bitMatrix (a b : ℕ) (w : BitWord (a*b)) : List.ofFn w=(List.ofFn (fun i => List.ofFn (bitMatrixEquiv a b w i))).flatten := by rw [List.ofFn_mul] apply congrArg List.flatten apply congrArg List.ofFn funext i apply congrArg List.ofFn funext j rw [bitMatrix_apply] congr 1 apply Fin.ext simp [finProdFinEquiv,Nat.mul_comm,Nat.add_comm] lemma chunks_bitMatrix (a b : ℕ) (w : BitWord (a*b)) : chunkValues a b (List.ofFn w)=List.ofFn (fun i => List.ofFn (bitMatrixEquiv a b w i)) := by rw [ofFn_bitMatrix,chunkValues_ofFn] lemma run_banksCode_four {n : ℕ} (O : IndependenceOracle n) (R M D H : ℕ) (w : BitWord (R*(M*(D*H)))) : run O banksCode (List.ofFn w,(R,(M,(D,H))))= some (List.ofFn (fun i => bankEncode (fourBitEquiv R M D H w i))) := by rw [run_banksCode] simp only [chunks_bitMatrix,List.map_ofFn,Function.comp_def] rfl lemma ofFn_finCongr {a b : ℕ} (h : a=b) (w : BitWord a) : List.ofFn w=List.ofFn ((Equiv.arrowCongr (finCongr h) (Equiv.refl Bool)) w) := by subst b rfl lemma run_reshapeCode_four {n : ℕ} (O : IndependenceOracle n) (R M H : ℕ) (w : BitWord (R*(M*((M+6)*H)))) : run O reshapeCode (List.ofFn w,(R,(M,H)))= some (List.ofFn (fun i => bankEncode (fourBitEquiv R M (M+6) H w i))) := by change run O banksCode (List.ofFn w,(R,(M,(M+6,H))))=_ exact run_banksCode_four O R M (M+6) H w lemma run_reshapeCode_cast {n a : ℕ} (O : IndependenceOracle n) (R M H : ℕ) (h : a=R*(M*((M+6)*H))) (w : BitWord a) : run O reshapeCode (List.ofFn w,(R,(M,H)))= some (List.ofFn (fun i => bankEncode (fourBitEquiv R M (M+6) H ((Equiv.arrowCongr (finCongr h) (Equiv.refl Bool)) w) i))) := by subst a exact run_reshapeCode_four O R M H w def bankReshapeEquiv {a : ℕ} (R M H : ℕ) (h : a=R*(M*((M+6)*H))) : BitWord a ≃ (Fin R → Fin M → Fin (M+6) → BitWord H) := (Equiv.arrowCongr (finCongr h) (Equiv.refl Bool)).trans (fourBitEquiv R M (M+6) H) lemma run_reshapeCode_equiv {n a : ℕ} (O : IndependenceOracle n) (R M H : ℕ) (h : a=R*(M*((M+6)*H))) (w : BitWord a) : run O reshapeCode (List.ofFn w,(R,(M,H)))= some (List.ofFn (fun i => bankEncode (bankReshapeEquiv R M H h w i))) := by exact run_reshapeCode_cast O R M H h w lemma reshape_count (n : ℕ) (ε δ : ℚ) : let L := annealLength n (accuracyExponent ε) let N := sampleCount n L ε let M := algorithmDrawBound n N L let H := drawWordBound n N L fairBitCount n ε δ=repetitionCount δ*(M*((M+6)*H)) := by change repetitionCount δ * drawWordBound n (sampleCount n (annealLength n (accuracyExponent ε)) ε) (annealLength n (accuracyExponent ε)) * _ * _ = _ ac_rfl def reshapeWordEquiv (n : ℕ) (ε δ : ℚ) : BitWord (fairBitCount n ε δ) ≃ FPRASBank n ε δ := bankReshapeEquiv (repetitionCount δ) (algorithmDrawBound n (sampleCount n (annealLength n (accuracyExponent ε)) ε) (annealLength n (accuracyExponent ε))) (drawWordBound n (sampleCount n (annealLength n (accuracyExponent ε)) ε) (annealLength n (accuracyExponent ε))) (reshape_count n ε δ) lemma run_reshapeCode_source {n : ℕ} (O : IndependenceOracle n) (ε δ : ℚ) (w : BitWord (fairBitCount n ε δ)) : let L := annealLength n (accuracyExponent ε) let N := sampleCount n L ε run O reshapeCode (List.ofFn w,(repetitionCount δ,(algorithmDrawBound n N L,drawWordBound n N L)))= some (List.ofFn (fun i => bankEncode (reshapeWordEquiv n ε δ w i))) := by exact run_reshapeCode_equiv O _ _ _ (reshape_count n ε δ) w open Expression open scoped Classical lemma run_preamble_generic {n : ℕ} (O : IndependenceOracle n) (x : Value FrozenData) (F : ℕ) (p : Value PreparedData) (hF : run O frozenBitCount x=some F) (hp : run O frozenPrepared x=some p) : ∃ counter : Word,counter.length=F ∧ run O preambleCode x=some (counter,p) := by obtain ⟨counter,hc,hl⟩ := run_unary O F refine ⟨counter,hl,?_⟩ simp only [preambleCode,run_both,run_compose,hF,hc,hp,Option.bind_some,Option.map_some] lemma run_preambleCode {n : ℕ} (O : IndependenceOracle n) (r : ℕ) (ε δ : ℚ) (hε : 0<ε) : ∃ counter : Word,counter.length=fairBitCount n ε δ ∧ run O preambleCode (frozenValue n r ε δ)=some (counter,preparedValue n r ε δ) := by exact run_preamble_generic O _ _ _ (run_frozenBitCount O r ε δ hε) (run_frozenPrepared O r ε δ hε) lemma run_reshapePrepared_generic {n : ℕ} (O : IndependenceOracle n) (w : Word) (p : Value AlgorithmParams) (shape : Value BankShape) (banks : Value (.list BankData)) (h : run O reshapeCode (w,shape)=some banks) : run O reshapePrepared (w,(p,shape))=some (p,banks) := by simp only [reshapePrepared,run_both,run_compose,run_fst,run_snd,Option.bind_some,Option.map_some,h] lemma run_reshapePrepared {n : ℕ} (O : IndependenceOracle n) (r : ℕ) (ε δ : ℚ) (w : BitWord (fairBitCount n ε δ)) : let L := annealLength n (accuracyExponent ε) let N := sampleCount n L ε run O reshapePrepared (rawValue n r ε δ w)= some (params n r N L,List.ofFn (fun i => bankEncode (reshapeWordEquiv n ε δ w i))) := by exact run_reshapePrepared_generic O _ _ _ _ (run_reshapeCode_source O ε δ w) def OutputCertificate {n : ℕ} (r : ℕ) (M₁ M₂ : Matroid (Fin n)) (O : IndependenceOracle n) (ε δ : ℚ) (v : BitWord (fairBitCount n ε δ) → ℚ) : Prop := (∀ w,run O postambleCode (rawValue n r ε δ w)=some (rationalPair (v w))) ∧ (∀ w,0≤v w ∧ (commonBaseCount M₁ M₂=0 → v w=0)) ∧ (∀ φ : ℚ → ℝ,uniformAverage (fun w => φ (v w))= uniformAverage (fun banks : FPRASBank n ε δ => φ (canonicalBoundedOutput n r O ε δ banks))) lemma output_certificate {n : ℕ} (r : ℕ) (M₁ M₂ : Matroid (Fin n)) (O : IndependenceOracle n) (hO : ExactOracles M₁ M₂ O) (hE₁ : M₁.E=Set.univ) (hE₂ : M₂.E=Set.univ) (hr₁ : M₁.eRank=(r:ℕ∞)) (hr₂ : M₂.eRank=(r:ℕ∞)) (ε δ : ℚ) : ∃ v,OutputCertificate r M₁ M₂ O ε δ v := by let L := annealLength n (accuracyExponent ε) let N := sampleCount n L ε by_cases hn : 0 treeBanksOutput u (List.ofFn (fun i => bankEncode (reshapeWordEquiv n ε δ w i))) refine ⟨v,?_,?_,?_⟩ · intro w rw [postambleCode,run_compose,run_reshapePrepared,Option.bind_some] have hz : ∀ bank∈List.ofFn (fun i => bankEncode (reshapeWordEquiv n ε δ w i)), 0≤(bankEval u bank).1.join.getD 0 := fun bank _ => (treeBankOutput_all u _ huall bank).1 have hh := run_amplifiedCode O (params n r N L) u he _ hz have hc : run O (Expression.compose fst (Expression.compose fst (Expression.compose fst natEqZero)) : Expression AmplifyInput .bool) (params n r N L,List.ofFn (fun i => bankEncode (reshapeWordEquiv n ε δ w i)))=some false := by simp [params,run_natEqZero,run_compose,run_fst,ne_of_gt hn] rw [finishCode,run_applyIf,hc,Option.bind_some] simp only [Bool.false_eq_true,ite_false] exact hh · intro w; exact treeBanksOutput_all u _ huall _ · intro φ have hfit := canonicalAlgorithmTree_fits n hn r O N L M₁ M₂ hO hE₁ hE₂ hr₁ hr₂ (by dsimp [N,sampleCount]; omega) have hb := reindexed_banks_law hu (drawWordBound n N L) (algorithmDrawBound n N L+6) (algorithmDrawBound n N L) (repetitionCount δ) hfit φ calc _ = uniformAverage (fun banks : FPRASBank n ε δ => φ (treeBanksOutput u (List.ofFn (fun i => bankEncode (banks i))))) := uniformAverage_equiv (reshapeWordEquiv n ε δ) _ _ = _ := by simpa only [canonicalBoundedOutput,dite_eq_left hn, canonicalAmplifiedOutput,canonicalFairOutput] using hb · refine ⟨fun _ => 1,?_,?_,?_⟩ · intro w rw [postambleCode,run_compose,run_reshapePrepared,Option.bind_some] have hc : run O (Expression.compose fst (Expression.compose fst (Expression.compose fst natEqZero)) : Expression AmplifyInput .bool) (params n r N L,List.ofFn (fun i => bankEncode (reshapeWordEquiv n ε δ w i)))=some true := by simp [params,run_natEqZero,run_compose,run_fst,show n=0 by omega] rw [finishCode,run_applyIf,hc,Option.bind_some,ite_eq_left rfl] rfl · intro w have hn0 : n=0 := by omega subst n simp [commonBaseCount_empty] · intro φ simp only [canonicalBoundedOutput,dite_eq_right hn,uniformAverage_const] open Expression lemma encode_natPair (z : Value NN) : encode z=pair z.1.bits z.2.bits := rfl lemma encode_rawValue (n r : ℕ) (ε δ : ℚ) (w : BitWord (fairBitCount n ε δ)) : encode (rawValue n r ε δ w)=pair (List.ofFn w) (encode (preparedValue n r ε δ)) := rfl lemma width_natPair (z : Value NN) : width z=2*z.1.bits.length+1+z.2.bits.length := by rw [width,encode_natPair,pair_length] lemma frozen_machine (fp fq : SizePolynomial) (n r : ℕ) (M₁ M₂ : Matroid (Fin n)) (O : IndependenceOracle n) (ε δ : ℚ) (hO : ExactOracles M₁ M₂ O) (hE₁ : M₁.E=Set.univ) (hE₂ : M₂.E=Set.univ) (hr₁ : M₁.eRank=(r:ℕ∞)) (hr₂ : M₂.eRank=(r:ℕ∞)) (hε : 0<ε) (hp : Safe O (fp.eval (masterParameter n r ε δ)) preambleCode (frozenValue n r ε δ)) (hq : ∀ w : BitWord (fairBitCount n ε δ), Safe O (fq.eval (masterParameter n r ε δ)) postambleCode (rawValue n r ε δ w)) (B : ℕ) (hB : (totalResourcePoly fp fq).eval (masterParameter n r ε δ)≤B) : ∃ (v : BitWord (fairBitCount n ε δ) → ℚ) (start : ℕ), OutputCertificate r M₁ M₂ O ε δ v ∧ start+3*fairBitCount n ε δ+1≤B ∧ ∀ bits : ℕ → Bool, let out := execution fprasBlock.code O (initialConfig 1 fprasBlock.size n r ε δ) bits B out.output=some (v (physicalWord start (fairBitCount n ε δ) bits)) ∧ out.oracleCalls≤B ∧ out.bitOperations≤B := by obtain ⟨v,hv⟩ := output_certificate r M₁ M₂ O hO hE₁ hE₂ hr₁ hr₂ ε δ obtain ⟨counter,hc,hpc⟩ := run_preambleCode O r ε δ hε have hn := (master_fields n r ε δ).1 have hpre := compile_majorant O preambleCode fp (masterParameter n r ε δ) hn _ _ hp hpc have hpost (w : BitWord (fairBitCount n ε δ)) : Bounded (compile postambleCode) O (pair (List.ofFn w) (encode (preparedValue n r ε δ))) (pair (rationalPair (v w)).1.bits (rationalPair (v w)).2.bits) ((compiledMajorant postambleCode fq).eval (masterParameter n r ε δ)) ∧ 2*(rationalPair (v w)).1.bits.length+1+(rationalPair (v w)).2.bits.length≤ fq.eval (masterParameter n r ε δ) := by constructor · have hm := compile_majorant O postambleCode fq (masterParameter n r ε δ) hn (rawValue n r ε δ w) (rationalPair (v w)) (hq w) (hv.1 w) rw [encode_rawValue,encode_natPair] at hm exact hm · have hw := safe_output (hq w) (hv.1 w) rw [width_natPair] at hw exact hw have hb := (totalResourcePoly_budget fp fq n r ε δ (rank_le_ground M₁ hr₁)).trans hB obtain ⟨start,hs,he⟩ := pipeline_budgeted_length O n.bits r.bits ε.num.natAbs.bits ε.den.bits δ.num.natAbs.bits δ.den.bits (compile preambleCode) (compile postambleCode) counter (encode (preparedValue n r ε δ)) (fairBitCount n ε δ) ((compiledMajorant preambleCode fp).eval (masterParameter n r ε δ)) ((compiledMajorant postambleCode fq).eval (masterParameter n r ε δ)) (fq.eval (masterParameter n r ε δ)) B hc hpre v (fun w => (hv.2.1 w).1) hpost hb exact ⟨v,start,hv,hs,he⟩ open scoped Classical lemma physical_accuracy {n : ℕ} (r : ℕ) (M₁ M₂ : Matroid (Fin n)) (O : IndependenceOracle n) (ε δ : ℚ) (hO : ExactOracles M₁ M₂ O) (hE₁ : M₁.E=Set.univ) (hE₂ : M₂.E=Set.univ) (hr₁ : M₁.eRank=(r:ℕ∞)) (hr₂ : M₂.eRank=(r:ℕ∞)) (hε : 0<ε) (hε1 : ε<1) (hδ : 0<δ) (v : BitWord (fairBitCount n ε δ) → ℚ) (hv : OutputCertificate r M₁ M₂ O ε δ v) (start B : ℕ) (hstart : start+3*fairBitCount n ε δ+1≤B) : (1-δ)*(2:ℚ)^B ≤ (Nat.card {bits : BitWord B // relativeAccuracy ε (commonBaseCount M₁ M₂) (v (physicalWord start (fairBitCount n ε δ) (finiteBits bits)))}:ℚ) := by have h := (canonical_bounded_fair_experiment n r O M₁ M₂ hO hE₁ hE₂ hr₁ hr₂ ε δ hε hε1 hδ).2 rw [←hv.2.2 (fun z => if relativeAccuracy ε (commonBaseCount M₁ M₂) z then (1:ℝ) else 0)] at h rw [←physicalWord_law start (fairBitCount n ε δ) B hstart (fun w => if relativeAccuracy ε (commonBaseCount M₁ M₂) (v w) then (1:ℝ) else 0)] at h rw [uniformAverage_indicator_card] at h have hcard : Fintype.card (BitWord B)=2^B := by simp [BitWord] rw [hcard,Nat.cast_pow,Nat.cast_ofNat] at h have hh := (le_div_iff₀ (by positivity : (0:ℝ)<2^B)).mp h exact_mod_cast hh end MachineCode end CommonBasesFPRAS open CommonBasesFPRAS CommonBasesFPRAS.MachineCode theorem common_bases_fpras : CommonBasesFPRAS.MainTheorem := by classical obtain ⟨fp,fq,hs⟩ := frozen_uniform_safe let p := totalResourcePoly fp fq refine ⟨1,fprasBlock.size,fprasBlock.code,p.coefficient*2^p.degree+1,p.degree,by omega,?_⟩ intro n r M₁ M₂ O ε δ hE₁ hE₂ hr₁ hr₂ hO hε hε1 hδ hδ1 have hh := hs n r M₁ M₂ O ε δ hO hE₁ hE₂ hr₁ hε let B := resourceBound (p.coefficient*2^p.degree+1) p.degree n r ε δ have hB : p.eval (masterParameter n r ε δ)≤B := p.monomial_bound _ (master_pos n r ε δ) obtain ⟨v,start,hv,hstart,he⟩ := frozen_machine fp fq n r M₁ M₂ O ε δ hO hE₁ hE₂ hr₁ hr₂ hε hh.1 hh.2 B hB constructor · intro bits have h := he bits refine ⟨?_,h.2.1,h.2.2,?_⟩ · rw [h.1]; rfl · intro z hz rw [h.1] at hz have hez := Option.some.inj hz subst z exact hv.2.1 _ · have ha := physical_accuracy r M₁ M₂ O ε δ hO hE₁ hE₂ hr₁ hr₂ hε hε1 hδ v hv start B hstart have hpred (bits : BitWord B) : (∃ z,(execution fprasBlock.code O (initialConfig 1 fprasBlock.size n r ε δ) (finiteBits bits) B).output=some z ∧ relativeAccuracy ε (commonBaseCount M₁ M₂) z) ↔ relativeAccuracy ε (commonBaseCount M₁ M₂) (v (physicalWord start (fairBitCount n ε δ) (finiteBits bits))) := by rw [(he (finiteBits bits)).1] simp only [Option.some.injEq,exists_eq_left'] change (1-δ)*(2:ℚ)^B ≤ (Nat.card {bits : BitWord B // ∃ z, (execution fprasBlock.code O (initialConfig 1 fprasBlock.size n r ε δ) (finiteBits bits) B).output=some z ∧ relativeAccuracy ε (commonBaseCount M₁ M₂) z}:ℚ) simpa only [hpred] using ha end OAI